Reputation: 9522
So is it possible to get an instance of Property<T>
is Property
and, not knowing its generic T
type parameter, to call its methods?
private interface Property<T>
{
T Value { get;}
void DestroyEarth();
}
class MyProperty : Property<int>
{
public int Value{ get { return 1 }; }
public void DestroyEarth() { }
}
So I am wondering if I can call DestroyEarth()
on MyProperty instances received by a method like
void PropertyCaller(Property p){p.DestroyEarth();}
(Note: we do not define or have simple Property
class or interface nowhere )
Upvotes: 0
Views: 157
Reputation: 8008
What are you asking for is an automatic conversion between Property<T>
types to Property<object>
(i guess) in cases where you don't know the T and still want to call that instance in some way. This can't be done for various reasons (research "covariance/contravariance" in generic types for some insight on the problem space).
I recommend doing this conversion yourself and implement an IProperty
(non generic - see Marc's answer) interface on top of your Property<T>
class that has the same signature but with T written as object. Then implement by hand the call re-directions to the T methods with casts when needed.
Upvotes: 0
Reputation: 1063994
Edit:
with the question edit, I would say: declare a non-generic interface and move the methods that don't relate to T
, for example:
interface IProperty {
object Value { get;}
void DestroyEarth();
}
interface IProperty<T> : IProperty {
new T Value { get;}
}
class MyProperty : IProperty<int>
{
object IProperty.Value { get { return Value; } }
public int Value{get {return 1;} }
public void DestroyEarth(){}
}
and just code against IProperty
when you don't know the T
.
(a different answer, from before you posted code, is in the history, for reference)
Then you have:
void PropertyCaller(IProperty p) { p.DestroyEarth(); }
Of course, you could also just let the compiler figure out the T
:
void PropertyCaller<T>(IProperty<T> p) { p.DestroyEarth(); }
Upvotes: 2
Reputation: 43531
Your Property
class should has some implementation regardless to T
, and Property<T>
derives from Property
, with more implementation related to T
.
Upvotes: -1