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

标签 c# generics

假设我有这样一个类:

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 类型并访问任何特定于该类型的信息。 (至少不使用静态类型;您需要转向诸如反射之类的东西来做到这一点。)

关于c# - 可以在没有类型的情况下使用泛型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22023303/

相关文章:

c# - 使用 updatepanel 和母版页提交表单后设置 javascript ScrollTo

c# - 使用 post 将 C# 数组发送到 PHP Web 服务

c# - 动态创建ImageButton并将其onclick函数设置为ServerTransfer到另一个WebForm

c# - 这段代码中的什么导致了 C# 中的内存泄漏?

swift - 如何克服“"Generic parameter ' T' is not used in function signature”的错误?

c# - 为什么更新字符串 INotifyPropertyChanged 属性而不更新 List<string>?

Java泛型函数获取JSON

c# - 通过 Google Calendar API v3 创建重复事件

c# - 这个图案有名字吗

generics - 为什么 Send on trait implementations 的 trait bounds 被忽略?