简体   繁体   中英

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 .

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.

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:

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

where classInstance is an instance of an object of type className .

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 .

The problem here is that the C# compiler is only allowed to infer generics on the first parameter of a method. So the following IS allowed.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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