你能用"where"来要求c#中的属性吗?

jua*_*uan 32 c# generics attributes constraints where

我想创建一个只接受可序列化类的泛型类,可以用where约束来完成吗?

我正在寻找的概念是这样的:

public class MyClass<T> where T : //[is serializable/has the serializable attribute]
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 38

不,我不敢.你可以用限制做的唯一事情是:

  • where T : class - T必须是参考类型
  • where T : struct - T必须是不可为空的值类型
  • where T : SomeClass - T必须是SomeClass或派生自它
  • where T : ISomeInterface - T必须是ISomeInterface或实现它
  • where T : new() - T必须有一个公共无参数构造函数

各种组合是可行的,但不是全部.关于属性没什么.

  • @ user457104:这不会强制应用该属性,不。 (2认同)

Pat*_*son 7

我知道的; 你不能做这个.你有没有添加'Initialize'方法或类似的东西?

public void Initialize<T>(T obj)
{
     object[] attributes = obj.GetType().GetCustomAttributes(typeof(SerializableAttribute));
     if(attributes == null || attributes.Length == 0)
          throw new InvalidOperationException("The provided object is not serializable");
}
Run Code Online (Sandbox Code Playgroud)

我没有测试过这段代码,但我希望你明白我的观点.

  • 如果您要进行运行时测试,则IsDefined方法更简单:http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.isdefined.aspx (2认同)