繁体   English   中英

是否可以获得Class属性? C#

[英]Is it possible to get Class attributes? C#

我有一个使用泛型的课程。 这个类做了一些需要序列化的操作。 因此,将赋予myClass的类必须包含属性[Serializable()]。 是否可以请求一个属于它的类? 在设计时最好的情况下。

    [Serializable()]
    public class clsSchnappschuss<T>
    {
      //Some operations which need serialization
    }

因此,如果有人使用clsSchnappschuss,他必须提供DataType(T),并且我想请求T实现[Serializable()]。 这可能吗?

问候

您不能静态地请求存在属性(即在编译时),但在代码内部您可以检查T ,就像它是实际的类型名称一样。 例如,您可以请求其typeof ,并从中提取属性:

public class clsSchnappschuss<T> {
    static clsSchnappschuss() {
        if (Attribute.GetCustomAttribute(typeof(T), typeof(SerializableAttribute)) == null) {
            throw new InvalidOperationException(typeof(T).FullName +" is not serializable.");
        }
    }
}

请注意,我将检查放在静态构造函数中。 这将在为每个特定类型使用clsSchnappschuss<>任何其他代码之前执行一次。

如果您给定的类实现了ISerializeable接口,您可以遵循以下内容:

public class clsSchnappschuss<T> where T : ISerializable

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM