简体   繁体   English

C#如何使用作为通用类的通用方法参数

[英]C# How to use a generic method parameter that is a generic class

So I have the following code: 所以我有以下代码:

public Dictionary<int, Class1<Class2>> someDictionary;

public T DoThings<T, U>(int id) where T : Class1<U>, new() where U : Class2, new()
{
    T something = null;
    if (!someDictionary.ContainsKey(id))
    {
        something = new T();
        someDictionary.Add(id, something);
    }
    return something;
}

And I am getting this error while trying to add to someDictionary: 我在尝试添加到someDictionary时遇到此错误:

Argument 2: Cannot convert from 'T' to 'Class1 < Class2 >' 参数2:无法从'T'转换为'Class1 <Class2>'

Any help as to how to solve this, if it even can be solved would be greatly appriciated, thanks. 如果能解决这个问题,那么有关如何解决此问题的任何帮助将不胜感激,谢谢。

Luke. 路加

You should declare the generic class. 您应该声明泛型类。

public class ShouldOneClass<T,U> where T : Class1<U>, new() 
                                 where U : Class2, new()
{
    public Dictionary<int, T> someDictionary;
}

But if you don't want use generic class , replace generics type with interface. 但是,如果您不想使用通用类,请使用接口替换通用类型。

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

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