2021年4月25日星期日

What's the practical use to invoke a member using reflection

I saw some code like this below:

// obj is an instance of SomeType   MethodInfo mi = obj.GetType().GetTypeInfo().GetDeclaredMethod("GetString");  String s = (String)mi.Invoke(obj, null);  

and SomeType class is

public class SomeType {    ...    public string GetString() {       return ...    }  }  

My question is, what is the extra benefit to invoke the member via MethodInfo.Invoke method when the first parameter of Invoke method is object which is already an instance of SomeType and you can simply do

String s = ((SomeType)obj).GetString();  

isn't this approach more straightforward?

https://stackoverflow.com/questions/67260004/whats-the-practical-use-to-invoke-a-member-using-reflection April 26, 2021 at 10:05AM

没有评论:

发表评论