【问题标题】:Generic of type T where T has a specific attributeT 类型的泛型,其中 T 具有特定属性
【发布时间】:2012-07-04 16:48:10
【问题描述】:

是否可以创建T 类型的泛型方法,其中T 具有特定属性?

例如:

public static XmlDocument SerializeObjectToXml<T>(T obj)
{
    //...
}

并且我只想序列化具有Serializable 和/或DataContract 属性的类:

[Serializable]
[DataContract(Name = "viewModel", Namespace = "ns")]
internal class ViewModel
{
    //...
}

【问题讨论】:

  • 你要问,那会是通用的吗?

标签: c# generics attributes serializable


【解决方案1】:

恐怕没有。有 3 种类型的约束:派生、构造函数和引用/值类型。

我相信,您应该检查方法主体中的属性,如果可序列化对象不符合条件,请调用不同的方法来处理它。

【讨论】:

    【解决方案2】:

    也许你可以间接地做到这一点,通过创建一个具有 Serializable 属性的基类,并为你的泛型类添加一个约束,以便类型参数应该从该基类继承:

    [Serializable]
    public class MyBase {}
    
    public static XmlDocument SerializeToXml<T>( T obj ) where T : MyBase {}
    

    【讨论】:

    • 请记住,并非所有属性都是可继承的。声明自定义属性时,您必须使它们可继承才能使用此方法:[System.AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)]
    【解决方案3】:

    静态地,我不这么认为。但是你可以在运行时检查类型 T:

    var isDataContract = typeof(T).GetCustomAttributes(typeof(DataContractAttribute), true).Any();
    if (!isDataContract) throw new InvalidOperationException("You can only serialize classes that are marked as data contracts.");
    //... continue serialization
    

    【讨论】:

    • 为什么需要 .Cast.Any()?既然您在 GetCustomAttributes() 调用中指定了 DataContractAttribute,那么返回的 object[] 的长度不应该大于 0 就足够测试了吗?
    猜你喜欢
    • 2020-08-08
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2015-11-18
    相关资源
    最近更新 更多