开发者

Is it possible to generalize a Tuple property?

I'm looking for a way that a Tuple property can receive several tuples like Tuple<int>, Tuple<string>. The next code is an example that I'm trying to do:

public class A
{
    public virtual Tuple Condition
    {
        get;
        set;
    }
}

public class B: A
{
    public override Tuple<int, string> Condition
    {
        get;
        set;
    }
}

I'd like to use the Condition property from A class, and 开发者_高级运维use it in other classes like B and asign it an specific Tuple.

B b = new B();
B.Condition = Tuple.Create(2, "Bella");

A a = b;
a.Condition  // Here must show B.Condition


Two problems with this approach:

  1. Tuple<T1, T2> and Tuple are different classes, and method/property overrides don't support polymorphism in the return types.

  2. Even if they did, Tuple<T1, T2> does not inherit from Tuple, so it wouldn't work anyway.

You would need to declare the virtual property to be of object and then just cast back and forth when needed. Alternatively, you may want to think about what your Condition property really represents; perhaps a custom class will prove more flexible than Tuples.


No, you can't because the signature does not match.

The closest pattern you may consider is the following:

public class A
{
    public object Condition
    {
        get;
        set;
    }
}

public class B: A
{
    public void SetCondition(Tuple<int, string> condition)
    {
        base.Condition = condition;
    }
}

However, what you are looking for has a limited sense. In which way could you use a "generic" Tuple? At this point it's better to think to an object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜