简体   繁体   中英

C# generic class accepting a inherited type.

**Preface I'm very new to generics. I have a class I created called Geno. My Peno class simply contains a string Name property. I'm wondering why I cannot call T.Name from within a method on this class. How would I access the properties on T? Any good resources on how this works?

public class Geno<T> where T : Peno
{

}

public string GetName()
{
   return T.Name;
}

Is your Name property an instance property or a static property? If it's a static property, you don't get polymorphism anyway - you could just call Peno.Name .

If it's an instance property, you need an instance on which to call it. For example:

public class Geno<T> where T : Peno
{
    private readonly T value;

    public Geno(T value)
    {
        this.value = value;
    }

    public string GetName()
    {
       return value.Name;
    }    
}

If this doesn't help, please give a more complete example of what you're trying to do.

T is the type Peno . So what you try to do is Peno.Name , which is probably not what you want. Something like this would work:

public string GetName(T t)
{
    return t.Name;
}

Static properties does not support inheritence. Hence you can just call Peno.Name rather than going for T.

If in your case you want to access a normal property, you need to create an instance of T which will let you call its property Name.

T is a Generic Type Parameter, not a parameter being passed into the class that is using T.

A Good example of this is List<T> you say this is a List, which means you are creating a list that contains object of the type of String.

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