J
Jeff Stewart
I've got several classes that are all concrete implementations of an
abstract class. I have a separate comparer class full of AreEqual()
methods, each with a signature that accepts a pair of concrete classes:
AreEqual(ConcreteA x, ConcreteA y)
AreEqual(ConcreteB x, ConcreteB y)
etc.
I've got another method designed to compare arrays of concrete types.
I'd like to have a single method,
AreEqual(Abstract[] x, Abstract[] y)
that calls the appropriate AreEqual() function above for all
permutations of the elements in the arrays.
Of course, the compiler wouldn't let me do this at compile-time, 'cause
even though the arrays are full of concrete instances, it can't perform
the (widening?) conversion from Abstract to ConcreteA or ConcreteB or
whatever the type may be.
So I started investigating reflection, and came up with this solution:
I created an additional AreEqual() method,
public bool AreEqual(Abstract x, Abstract y) {
Type t = this.GetType();
return (bool)t.InvokeMember("AreEqual", BindingFlags.InvokeMethod,
null, this, new Object[] {x, y});
}
And it works fine! I use that method in my array comparison and it
seems to work like a charm. But I'm worried that this was too easy,
and that I'm missing something. (The BindingFlags don't all seem to be
very clear.) Should it really be so trivial to bypass compile-time
type checking? Am I "cheating" doing this?
abstract class. I have a separate comparer class full of AreEqual()
methods, each with a signature that accepts a pair of concrete classes:
AreEqual(ConcreteA x, ConcreteA y)
AreEqual(ConcreteB x, ConcreteB y)
etc.
I've got another method designed to compare arrays of concrete types.
I'd like to have a single method,
AreEqual(Abstract[] x, Abstract[] y)
that calls the appropriate AreEqual() function above for all
permutations of the elements in the arrays.
Of course, the compiler wouldn't let me do this at compile-time, 'cause
even though the arrays are full of concrete instances, it can't perform
the (widening?) conversion from Abstract to ConcreteA or ConcreteB or
whatever the type may be.
So I started investigating reflection, and came up with this solution:
I created an additional AreEqual() method,
public bool AreEqual(Abstract x, Abstract y) {
Type t = this.GetType();
return (bool)t.InvokeMember("AreEqual", BindingFlags.InvokeMethod,
null, this, new Object[] {x, y});
}
And it works fine! I use that method in my array comparison and it
seems to work like a charm. But I'm worried that this was too easy,
and that I'm missing something. (The BindingFlags don't all seem to be
very clear.) Should it really be so trivial to bypass compile-time
type checking? Am I "cheating" doing this?