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:
Tuple<T1, T2>
andTuple
are different classes, and method/property overrides don't support polymorphism in the return types.Even if they did,
Tuple<T1, T2>
does not inherit fromTuple
, 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 Tuple
s.
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.
精彩评论