简体   繁体   中英

C# Get the name of an object without knowing its Type

private void function(object sender, EventArgs e)

Is it possible to get the Name, without using a variable?

if(sender.getType().Name == "Button") {
    Button btn = sender as Button;
    ObjName = btn.Name
}

if(sender.getType().Name == "CheckBox") {
    CheckBox cbx= sender as CheckBox;
    ObjName = cbx.Name
}

I have a function that works with a lot of different object types, and the only thing I need is the Name.

只需将其转换为基本类型Control

var name = ((Control)sender).Name

Also, if the base type is not the same you could you reflection as follows:

private  void function(object sender)
{
     if (sender != null && sender.GetType().GetProperty("Name") != null)
        {
            var val = sender.GetType().GetProperty("Name").GetValue(sender);
        } 
}

In the case where you can't use a common base type, such as if you are dealing with items from WinForms & WPF simultaneously, you can use reflection to check if the item has a name property, and then if it does return that value.

public string GetNameIfExists(dynamic item)
{
    if (item.GetType().GetProperty("Name") != null)
    {
        return item.Name;
    }
    return null;
}

This pattern is more common than checking the type name:

var btn = sender as button;
if (btn != null) // it's a button
{
    //...
    return;
}
var chkbx = sender as checkbox;
if (chkbx != null) // it's a checkbox
{
   //...
   return;
}

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