Is it possible to make an object expose the interface of an type parameter?

后端 未结 2 1439
盖世英雄少女心
盖世英雄少女心 2021-01-05 06:40

In C#, is it possible to write something like this:

public class MyClass : T 
    where T : class, new() 
{
}

I know that the abov

2条回答
  •  难免孤独
    2021-01-05 07:12

    You could have a look at DynamicObject and do something like this:

    class Foo : DynamicObject
    {
        private T _instance;
        public Foo(T instance)
        {
            _instance = instance;
        }
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            var member = typeof(T).GetProperty(binder.Name);
            if (_instance != null &&
                member.CanWrite &&
                value.GetType() == member.PropertyType)
            {
                member.SetValue(_instance, value, null);
                return true;
            }
            return false;
        }
    
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            var member = typeof(T).GetProperty(binder.Name);
            if (_instance != null &&
                member.CanRead)
            {
                result = member.GetValue(_instance, null);
                return true;
            }
            result = null;
            return false;
        }
    }
    
    class Bar
    {
        public int SomeProperty { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var bar = new Bar();
            dynamic thing = new Foo(bar);
            thing.SomeProperty = 42;
            Console.WriteLine(thing.SomeProperty);
            Console.ReadLine();
        }
    }
    

提交回复
热议问题