简体   繁体   中英

C# Generics and types

I have a generic method something like:

public abstract T method<T>(int arg) where T : class, new();

Then I implement it in the child class

public MyType method<MyType>(int arg){
    MyType e = new MyType();

    e.doStuff (arg); // ERROR HERE

    return s;
}

But I can't access MyType's members... How come ? Is there something I can add to enable them or something ?

Thank you

Miloud

C# does not have template specialization. You nave simply declared a new method with the type-parameter named MyType , which has nothing to do with the class named MyType .

You can cast , or there are generic constraints you use to declare that T is at least a MyType .

Another option would be to make the base-type itself generic in T (and remove the generic from the method), and have the concrete type : TheBaseType<MyType>

You can do like this (note that I have moved some of your generic parameters and constraints around).

public class MyType
{
    public void doStuff(int i){}
}
public abstract class ABase<T>where T : class, new()
{
    public abstract T method(int arg);
}

public class AChild : ABase<MyType>
{
    override public MyType method(int arg)
    {
        MyType e = new MyType();

        e.doStuff(arg); // no more error here

        return e;
    }
}

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