Using Reflection.Emit to create a class implementing an interface

前端 未结 5 523
暗喜
暗喜 2020-12-14 04:03

I need to generate a class using Reflection.Emit that implements the following interface.

public interface IObject
{
    T Get(string propertyName);         


        
5条回答
  •  感动是毒
    2020-12-14 04:28

    It seems, you want to make fast access to object's properties by its name without reflection at run time. Using Yappi and its Property<> class you can implement given interface like this:

    class GeneratedObject : IObject
    {
        public string Value { get { return "Test"; } }
    
        public T Get(string propertyName)
        {
            return Property.Get(this,propertyName);
        }
    }
    

    and then use it like this:

    IObject obj = new GeneratedObject();
    var value = obj.Get("Value"); //value contains "Test"
    

    Do you still need IObject and dynamic type construction?

提交回复
热议问题