猿问

根据通用接口获取类属性

可以说我有这个:


public interface IMyInterface<T>

{

}


public class MyClass

{

    public IMyInterface<Foo> Foos {get; set;}

    public IMyInterface<Bar> Bars {get; set;}

}

我想要一个这样的方法


MyClass.Interfaces<T>()

哪个将返回 MyClass.Foos 或 MyClass.Bars 取决于 T 值。我怎么做?这与 EF 的工作方式非常相似。



泛舟湖上清波郎朗
浏览 145回答 2
2回答

函数式编程

它需要一些管道和铸造,但你可以用字典来做到这一点:public interface IMyInterface<T> {}public class Foo { }public class Bar { }public class MyClass {&nbsp; &nbsp; Dictionary<Type, object> myInterfaces = new Dictionary<Type, object>();&nbsp; &nbsp; public IMyInterface<Foo> Foos {&nbsp; &nbsp; &nbsp; &nbsp; get { return (IMyInterface<Foo>)myInterfaces[typeof(Foo)]; }&nbsp; &nbsp; &nbsp; &nbsp; set { myInterfaces[typeof(Foo)] = value; }&nbsp; &nbsp; }&nbsp; &nbsp; public IMyInterface<Bar> Bars {&nbsp; &nbsp; &nbsp; &nbsp; get { return (IMyInterface<Bar>)myInterfaces[typeof(Bar)]; }&nbsp; &nbsp; &nbsp; &nbsp; set { myInterfaces[typeof(Bar)] = value; }&nbsp; &nbsp; }&nbsp; &nbsp; public IMyInterface<T> Interfaces<T>() {&nbsp; &nbsp; &nbsp; &nbsp; return (IMyInterface<T>)myInterfaces[typeof(T)];&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答