简体   繁体   中英

Easiest way to dynamically get/set properties of c# objects by name

I have several objects of different types and the name of a property that I need to get and set on these. In languages like javascript this is trivial as I can get and set values with indexor syntax.

obj2[propertyName] = obj1[propertyName];

In c# it's not so easy. I know I can use reflection but that's a lot of code. I know there's dynamic objects, but they don't automatically have a way to reference properties by name. What's the easiest way to get and set properties dynamically by name on objects of arbitrary types (ie they have the property but don't all share a common interface or base class)?

Update: Upon further research it seems like FastMember, Impromptu, Dynamitey, or maybe FSharp.Dynamic can help here if anyone has any thoughts...

At risk of oversimplifying the solution, why not create a pair of extension methods off the object type that abstract the reflection code? Methods like

static void SetProperty<T>(this object, string propertyName, T propertyValue) 
static T GetProperty<T>(this object, string propertyName)

Usage would be not quite as your question describes:

obj2.SetProperty("ArbitraryPropertyName", obj1.GetProperty("AribraryPropertyName");

dynamic value in property object:

public dynamic propertyName {
   get; set;
}

to get a property by name, you need to implement an indexer in the class https://www.geeksforgeeks.org/c-sharp-indexers/

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