简体   繁体   English

将泛型传递到类构造函数列表

[英]Passing generic into a class constructor list

I have a class that takes a generic as a parameter like this 我有一个类,将这样的泛型作为参数

public MyNewClass(string text, T myClass, int f, bool test = false)

The compiler is complaining about T myClass . 编译器抱怨T myClass

I know I can pass "defined" generic classes to a class constructor (such as List , Dictionary etc) and have seen that this can be done in C# as well, but can't find a reference to it. 我知道我可以将“定义的”泛型类传递给类构造函数(例如ListDictionary等),并且已经看到这也可以在C#中完成,但是找不到对它的引用。

You should declare the generic parameter, when you declare your class. 声明类时,应声明通用参数。

public class MyNewClass<T>
{


}

Then this parameter could be accessible from any of the class's methods. 然后可以从任何类的方法访问此参数。 When you will create an instance of your MyNewClass , you should define also the type of T, for instance: 当创建MyNewClass的实例时,还应该定义T的类型,例如:

var instanceOfMyNewClass = new MyNewClass<className>(text, classIntance, f, true);

where classInstance is an instance of an object of type className . 其中classInstanceclassName类型的对象的实例。

A good introduction about generics is here . 关于泛型一个很好的介绍是这里

I suspect that the issue you are facing is that the following does not compile 我怀疑您面临的问题是以下内容无法编译

public class Foo<T>
{
    public Foo(string s, T t) { }
}

var foo = new Foo("Hello", new Something());

The fix to this is to specify in the constructor. 解决方法是在构造函数中指定。

var foo = new Foo<Something>("Hello", new Something());

However, this still seems a little strange given that normally, the C# compiler can infer the type of T . 但是,考虑到通常C#编译器可以推断T的类型,这似乎仍然有些奇怪。

The problem here is that the C# compiler is only allowed to infer generics on the first parameter of a method. 这里的问题是C#编译器仅允许在方法的第一个参数上推断泛型。 So the following IS allowed. 因此允许以下。

public class Foo<T>
{
    public Foo(T t, string s) { }
}

var foo = new Foo(new Something(), "Hello");

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

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