开发者

C# generic class accepting a inherited type.

开发者 https://www.devze.com 2023-03-23 17:43 出处:网络
**Preface I\'m very new to generics. I have a class I created called Geno. My Peno class simply contains a string Name p开发者_如何学Goroperty. I\'m wondering why I cannot call T.Name from within a me

**Preface I'm very new to generics. I have a class I created called Geno. My Peno class simply contains a string Name p开发者_如何学Goroperty. 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.

0

精彩评论

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