Skip to main content
 首页 » 编程设计

c#之可以在没有类型的情况下使用泛型吗

2024年02月13日10jackei

假设我有这样一个类:

public class MyClass<T> where T : BaseClass, new() 
{ 
    public Boolean DoWork() 
    { 
        // do the work, obviously. 
    } 
} 

并且在某些方法中我需要 DoWork()在一些MyClass<T>我不需要知道T .据我所知,我需要引用我的MyClass<T>参数并重申 T 的约束,像这样:

public void DoLotsOfWork(MyClass<T> item) where T : BaseClass, new() 
{ 
    // do some work 
 
    // no need to know what T is here: 
    item.DoWork(); 
 
    // maybe do some other work. 
} 

可以方法DoLotsOfWork()引用MyClass<T> 没有重申对 T 的限制?(或者甚至可能知道 T?)

请您参考如下方法:

处理这个问题的方法是使 DoLotsOfWork 通用。

public void DoLotsOfWork<T>(MyClass<T> item) where T : BaseClass, new() 
{ 
    // do some work 
 
    // no need to know what T is here: 
    item.DoWork(); 
 
    // maybe do some other work. 
} 

在不提供任何通用参数的情况下,您不能引用 MyClass 类型并访问任何特定于该类型的信息。 (至少不使用静态类型;您需要转向诸如反射之类的东西来做到这一点。)