简体   繁体   中英

C#.NET Generic Methods and Inheritance

Is it possible to do the following with generics in C#.NET

public abstract class A
{
    public abstract T MethodB<T>(string s);
}

public class C: A
{
    public override DateTime MethodB(string s)
    {
    }
}

ie have a generic method in a base class and then use a specific type for that method in a sub class.

The type parameter should be declared with the type, and the subclass will declare the specific type in its inheritance declaration:

public abstract class A<T>
{ 
    public abstract T MethodB(string s); 
} 

public class C: A<DateTime> 
{ 
    public override DateTime MethodB(string s) 
    { 
        ...
    } 
} 

No.

The reason is that you would be providing implementation only for one special case. The base class requires you to implement a MethodB that can work for any type T . If you implement it only for DateTime and if someone calls, for example, ((A)obj).MethodB<int> then you don't have any implementation that could be used!

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