Can you use “where” to require an attribute in c#?

百般思念 提交于 2019-11-26 11:20:29

问题


I want to make a generic class that accepts only serializable classes, can it be done with the where constraint?

The concept I\'m looking for is this:

public class MyClass<T> where T : //[is serializable/has the serializable attribute]

回答1:


Nope, I'm afraid not. The only things you can do with constraints are:

  • where T : class - T must be a reference type
  • where T : struct - T must be a non-nullable value type
  • where T : SomeClass - T must be SomeClass or derive from it
  • where T : ISomeInterface - T must be ISomeInterface or implement it
  • where T : new() - T must have a public parameterless constructor

Various combinations are feasible, but not all. Nothing about attributes.




回答2:


What I know; you can not do this. Have you though about adding an 'Initialize' method or something similar?

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");
}

I haven't tested this code, but I hope that you get my point.




回答3:


Afraid not. Best you can do is a runtime check on Type.IsSerializable.




回答4:


If you are looking for any class that is serializable, I think you are out of luck. If you are looking for objects that you have created, you could create a base class that is serializable and have every class you want to support derive from it.




回答5:


I know this is old, but I am using a static constructor to check. It is later but allows you to throw an error at runtime.



来源:https://stackoverflow.com/questions/221687/can-you-use-where-to-require-an-attribute-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!