简体   繁体   中英

C# Generics: How to use nameof to get the name of a base class property

I have an inheritance hierarchy like the following:

public abstract class A
{
    public string MyProperty {get; set;}
}

public class B : A
{
    
}

public class C : A
{
   
}

I then have a method that uses generics:

public void MyMethod<T>() where T : A
{
    var str = nameof(T.MyProperty); // this one fails
}

I'm trying to get the name of MyProperty , but it fails because I'm trying to do this through a type instead of an object. Is there a clever way of getting the property name without having to pass an object?

nameof(A.MyProperty) .

You constraint T to be an A anyway.

Another option wold be to create "dummy" instance of T :

public void MyMethod<T>() where T : A
{
    var t = default(T);
    var str = nameof(t.MyProperty);
}

It seems that compiler is smart enough to remove this dummy instance in release configuration.

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