我有一个抽象类A和一个参数的抽象方法,它又是在同一个抽象类A中定义的抽象类B。当我把这个抽象类A扩展为另一个类C的一部分时,如何用嵌套抽象类的参数来实现这个方法。
public abstract class A<T, V>
{
public abstract int GetObject(T t, V v);
public abstract int GetAnotherObject(B b);
public abstract class B{}
}这个类由另一个C类扩展
public class C: A<ABC, DEF>
{
public C()
{
}
public override int GetObject(ABC abc, DEF def)
{
return 10;
}
public override int GetAnotherObject(B b)
{
return 15;
}
}如何用一些属性实现B类,并在GetAnotherObject方法中传递。有人能帮帮我吗。
发布于 2015-02-28 18:57:11
来自ECMA:
嵌套在泛型类声明或泛型结构声明(§25.2)中的任何类本身就是泛型类声明,因为应该提供包含类型的类型参数来创建构造的类型。
因此,如果不为B提供类型参数,就无法实现嵌套A。
void Main()
{
var c = new C();
var result = c.GetAnotherObject(new BImpl<string, int>());
}
public class BImpl<T, V> : A<T, V>.B
{
public override int BM()
{
return 1;
}
}
// Or you can supply type arguments right here
//public class BImpl : A<string, int>.B
//{
// public override int BM()
// {
// return 1;
// }
//}
public abstract class A<T, V>
{
public abstract int GetObject(T t, V v);
public abstract int GetAnotherObject(B b);
public abstract class B
{
public abstract int BM();
}
}
public class C : A<string, int>
{
public C()
{
}
public override int GetObject(string abc, int def)
{
return 10;
}
public override int GetAnotherObject(B b)
{
return b.BM();
}
}发布于 2015-02-28 19:02:34
你已经很亲密了。
public class C<ABC, DEF> : A<ABC, DEF>
{
public C()
{
}
public override int GetObject(ABC abc, DEF def)
{
return 10;
}
// since B is a nested class of A, it has no scope outside of A
// outside of the definition of A, it must always be referred to as A.B
public override int GetAnotherObject(A<ABC,DEF>.B b)
{
return 15;
}
}
public class D : A<ABC,DEF>.B
{
// implementation of A.B
}请记住,C总是采用精确的A.B。您将永远无法定义A.B的实现(让我们称之为D),并让C的方法签名引用覆盖中的方法签名。GetAnotherObject在A中定义为接受A.B,因此必须实现以接受任何A.B,而不是A.B的特定实现。
RE:您对如何在A.B中实现C的评论
在A.B中实现C没有任何意义。C在其方法签名中仍然必须有A.B。但如果你真的必须的话,出于某种原因。
public class C<ABC, DEF> : A<ABC, DEF>
{
// C's implementation of A
public override int GetAnotherObject(A<ABC,DEF>.B b)
{
return 15;
}
public class D : A<ABC,DEF>.B
{
// implementation of A.B
}
}请注意,GetAnotherObject仍然采用A.B,而不是D。
发布于 2015-02-28 18:52:39
怎么样
public class C<ABC, DEF> : A<ABC, DEF>
{
public C()
{
}
public override int GetObject(ABC abc, DEF def)
{
return 10;
}
public override int GetAnotherObject(B b)
{
return 15;
}
}只需在类后面加上泛型。
https://stackoverflow.com/questions/28785451
复制相似问题