0

那么是否有可能获取Property<T>is的实例,Property并且在不知道其泛型T类型参数的情况下调用其方法?

private interface Property<T> 
{
    T Value { get;}
    void DestroyEarth();
}

class MyProperty : Property<int>
{
    public int Value{ get { return 1 }; }
    public void  DestroyEarth() { }
}

所以我想知道我是否可以调用DestroyEarth()MyProperty 实例收到的方法,如

void PropertyCaller(Property p){p.DestroyEarth();}

(注意:我们没有定义或没有简单的Property类或接口 nowhere )

4

3 回答 3

2

编辑:

对于问题编辑,我会说:声明一个非通用接口并移动与 不相关的方法,T例如:

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(){}
}

IProperty你不知道T.

(与您发布代码之前不同的答案在历史记录中,供参考)

然后你有:

void PropertyCaller(IProperty p) { p.DestroyEarth(); }

当然,您也可以让编译器找出T

void PropertyCaller<T>(IProperty<T> p) { p.DestroyEarth(); }
于 2012-08-13T09:47:21.200 回答
0

在您不知道 T 并且仍想以某种方式调用该实例的情况下,您要求的是Property<T>类型之间的自动转换(我猜)。Property<object>由于各种原因(研究泛型类型中的“协方差/逆变”以获得对问题空间的一些见解),这无法完成。

我建议您自己进行此转换,并在您的类IProperty之上实现一个(非通用 - 请参阅 Marc 的答案)接口,该接口具有相同的签名但将 T 写为对象。Property<T>然后在需要时手动实现对 T 方法的调用重定向。

于 2012-08-13T10:56:23.027 回答
-1

你的Property类应该有一些实现,不管它T,并Property<T>派生自Property,与更多相关的实现T

于 2012-08-13T09:44:19.013 回答