开发者

C# Generics and types

开发者 https://www.devze.com 2023-01-25 18:23 出处:网络
I have a generic method something like: public abstract T method<T>(int arg) where T : class, new();

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


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;
    }
}


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>

0

精彩评论

暂无评论...
验证码 换一张
取 消