简体   繁体   English

如何确定类型是否实现接口并使用该接口的成员

[英]How to determine if a type implements an interface and use members of that interface

I am building a Vector<T> class and I am having differculties with an Add method. 我正在构建一个Vector<T>类,我与Add方法有不同之处。 What I already have is the interface that makes adding possible, but only if I know that T implements IAddable<TIn, TOut> . 我已经拥有的是可以添加的界面,但IAddable<TIn, TOut>是我知道T实现了IAddable<TIn, TOut>

interface IAddable<TIn, TOut>
{
    Vector<TOut> Add(Vector<TIn>)
}

partial Vector<T> where T : IAddable<T, T>
{
    public Vector<T> Add(Vector<T> v)
    {
        return mapIndexed((index, x) => this[index].Add(v[index]));
    }
}

The point is, I want to be able to add Vector<T> and Vector<TIn> to a Vector<TOut> for every T that implements IAddable<TIn, TOut> . 关键是,我希望能够为实现IAddable<TIn, TOut>每个TVector<TOut>添加Vector<T>Vector<TIn> IAddable<TIn, TOut> My solution below obviously doesn't work because you can't just call this[index].Add(v[index]) . 我的解决方案显然不起作用,因为你不能只调用this[index].Add(v[index]) Is there a way to call it without running into this kind of problems? 有没有办法调用它而不会遇到这种问题?

partial Vector<T>
{
    public Vector<TOut> Add<TIn, TOut>(Vector<TIn> v)
    {
        if (typeof(T).IsAssignableFrom(typeof(IAddable<TIn, TOut>)))
            return mapIndexed((index, x) => this[index].Add(v[index]));
        return null;
    }
}
If T.GetInterface("IAddable<TIn, TOut>") != null { /* Use in vector... */ }

Actually, no need for contrvariance here. 实际上,这里不需要控制。 The following will allow to add a Vector<T> into Vector<T2> only if T2 is derives from T 仅当T2T派生时,以下将允许将Vector<T>添加到Vector<T2>

public interface IMyVector<T>
{
    void AddVector<TIn>(IMyVector<TIn> vector) where TIn : T;
}

public class Vector<T> : IMyVector<T>
{
    public void AddVector<TIn>(IMyVector<TIn> vector) where TIn : T
    {
        // Your logic here
    }
}

public class Base {}

public class Derived : Base {}

And the test class: 和测试类:

public class Tests
{
    public void Test()
    {
        IMyVector<Base> baseVector= null;
        IMyVector<Derived> derivedVector= null;

        baseVector.AddVector(derivedVector);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM