简体   繁体   中英

C# How to Get a Object Attribute by String?

I have an Object (Player) with an Attribute (Name)

Player player = new Player()
{
   player.Name = "testName"
}

And I want to get that Attribute throw a string that i got from a [CallerMemberName]:

private void GetAttribute([CallerMemberName] string caller = "")
{
//Here the string caller is "Name"
//Isnt there a way i can do Like when i search Controls (Controls.Find(...))
//player.Find(caller);
}
string attributeString = "Name";

Thanks for the answer :D

Maybe Reflection is what you need:

class Program
{
    static void Main()
    {

        Player player = new Player();
        player.Name = "Foo";


        string valueOfName = typeof(Player).GetProperty("Name").GetValue(player).ToString();

        //valueOfName is now Foo

        typeof(Player).GetProperty("Name").SetValue(player, "Bar");
        //player.Name is now Bar
    }
}

class Player
{
    public string Name { get; set; }
}

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