获取类属性取决于通用接口

时间:2018-05-23 03:37:40

标签: c# generics

让我说我有这个:

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的工作方式非常相似。

2 个答案:

答案 0 :(得分:1)

它需要一些管道和铸造,但你可以用字典做到这一点:

public interface IMyInterface<T> {
}
public class Foo { }
public class Bar { }

public class MyClass {

    Dictionary<Type, object> myInterfaces = new Dictionary<Type, object>();

    public IMyInterface<Foo> Foos {
        get { return (IMyInterface<Foo>)myInterfaces[typeof(Foo)]; }
        set { myInterfaces[typeof(Foo)] = value; }
    }
    public IMyInterface<Bar> Bars {
        get { return (IMyInterface<Bar>)myInterfaces[typeof(Bar)]; }
        set { myInterfaces[typeof(Bar)] = value; }
    }

    public IMyInterface<T> Interfaces<T>() {
        return (IMyInterface<T>)myInterfaces[typeof(T)];
    }

}

答案 1 :(得分:0)

public class MyClass
{
    public IMyInterface<Foo> Foos { get; set; }
    public IMyInterface<Bar> Bars { get; set; }

    public IMyInterface<T> Interfaces<T>()
    {
        var property = GetType().GetProperties()
            .Where(x => x.PropertyType.Name.StartsWith("IMyInterface")
                        &&
                        x.PropertyType.GenericTypeArguments.Contains(typeof(T)))
            .FirstOrDefault();

        if (property != null)
            return (IMyInterface<T>)property.GetValue(this);
        return null;
    }
}