开发者

C# Dynamic indexer

Does anybody know if it's possible to call method on 开发者_JAVA技巧CLR object via indexer using dynamic lang features? For instance, myClrObj["SuperMethod"] () which I can easily do in javascript.

thank in advance.


There may be better ways, but one way I'd know how to do it is:

  • Create a class that inherits from DynamicObject
  • override the suitable method to capture the access via indexer
  • Construct and cache a delegate that corresponds to the method that you find via the provided indexer argument
  • Provide an extension method that suitably makes your object appear dynamic, with the correct DynamicObject specialization instantiated.

    dynamic obj = myObj.AsIndexedObj(); obj["Do"]();


You could use the opensource Dynamitey available via nuget, it wraps the DLR API to make it simpler to dynamically call a method by name, works for both dynamic and poco objects. Faster than reflection for poco objects.

Dynamic.InvokeMember(myClrObj,"SuperMethod")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜