Skip to main content
 首页 » 编程设计

c#之在编译时检查泛型参数

2024年02月23日11shanyou

假设我有以下类(class):

public class MyClass<T> 
{ 
    public MyClass() { 
        //construct logic 
    } 
 
    public IProperty<T> MyProperty { get; set; } 
} 
 
public interface IProperty<T> { } 
 
public DateTimeProperty : IProperty<DateTime> 
{ 
 
} 

如果我尝试将此代码放入 MyClass 的构造函数中:

if (typeof(T) == typeof(DateTime)) 
    MyProperty = new DateTimeProperty(); 

我得到以下编译错误:

Cannot implicitly convert type 'DateTimeProperty' to 'IProperty'

如何在 MyClass 的构造函数中将 MyProperty 的值设置为 new DateTimeProperty,前提是 T 的类型为 DateTime?

请您参考如下方法:

请注意,泛型实际上应该就是这样; 通用;你正在做的是特化(对于某些 T ),这不是重点。然而,至于如何 - Actor :

MyProperty = (IProperty<T>)(object)new DateTimeProperty(); 

通过转换为 object然后备份到(IProperty<T>)您删除了编译器应用静态类型检查规则的能力。缺点是:您消除了编译器应用静态类型检查规则的能力。