Using C # dynamic method for an object

I have a method that should return identifiers from a list. I usually use reflection for this task (I cannot use the general method, since classes are usually POCOS that do not use an interface or base class, and I cannot change them). However, I thought of a new dynamic key and wanted to try it.

However, my problem is that dataSource [index] returns an object. Well at runtime it is ensured that the iself object belongs to my own classes and has the id property. But I suppose, because the method returns an object, I get a RumtineBinderException at runtime when accessing current.id

 public List<int> GetItemIds() { var result = new List<int>(); var dataSource = GetDataSource(); // returns an List<Object> for (int i = 0; i <= dataSource.Count - 1; i++) { dynamic current = dataSource[i]; int id = current.Id; // throws RuntimeBinderException: Object has no definition for id } return result; } 

Is there a way to achieve what I want, or do I need to go back to thinking in order to get the id property?

Update:

 current.GetType() returns object current.GetType().GetProperties() returns a TargetInvocationException 

My Pocos live in my main project (VB.net), but this method is in the class library, maybe this is the reason. However:

 object current = dataSource[i]; PropertyInfo prop = current.GetType().GetProperty("id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (prop != null) { int id = (int)prop.GetValue(current, null); } 

work.

+6
source share
2 answers

I believe that you may need to define the return type " GetDataSource() " as " List<dynamic> ".

Of course, as pointed out in the comments, objects must have the id property.

+1
source

C # is case sensitive, including when using a dynamic keyword. your call int id = current.Id; but you are saying that the property is a string identifier and your reflection call looks case insensitive. The dynamic keyword should not have problems calling property of the public instance even at the assembly boundaries, since it says that the method was not found, and I think you need to use int id = current.Id;

+1
source

Source: https://habr.com/ru/post/892763/


All Articles