[英]How Interface reference is able to call child class methods?
接口引用如何能够调用子类方法。
在下面的示例中,接口引用如何访问Test类对象?
interface ITest
{
int add();
}
public class Test : ITest
{
public int add()
{
return 1;
}
public int sub()
{
return -1;
}
}
static void Main(string[] args)
{
ITest t = new Test();
Console.WriteLine((t as Test).sub());
}
-1。
这条线
Console.WriteLine((t为Test).sub());
将t
别名的任何内容强制转换为Test
类型。
您知道t
可转换为Test
因为您为其分配了Test
的实例
ITest t = new Test();
请注意,如果t
的类型不能转换为Test
,
t as Test
将评估为null,随后对.sub()的调用将导致NullReferenceException。
尽管这很少是一个好的设计选择,但是您可以做一些类似的事情
if (t is Test)
{
Console.WriteLine(((Test)t).sub());
}
else
{
Console.WriteLine("t cannot be converted to type Test");
}
或者
Test myTest = t as Test;
if (myTest != null)
{
Console.WriteLine(myTest.sub());
}
else
{
Console.WriteLine("t cannot be converted to type Test");
}
因为t
实际上是Test
类的一个实例。 将其存储到接口中并不仅限于接口方法(如果用作接口,则是,类型转换为Test
,然后否)。
例如类似:
IEnumerable<string> list = new List<string>();
list.Add("MyName"); // --> This won't compile since IEnumerable does not have Add method
(list as List<string>).Add("MyName"); // --> This will compile and execute, since underlying Type actually IS List<string>
但是很多时候,当我们使用接口时,我们并不知道实际的底层类型,所以这就是为什么这种类型的转换不那么常见的原因。
我认为它也被认为是不好的做法,但是我不确定。
正如埃里克(Eric)所指出的那样,我们不应该进行这种铸造。 这意味着我们的设计存在问题,我们应该考虑重新设计。
您正在从测试类中调用sub()
方法,因此,您将获得-1
的结果。 请指定您遇到的问题的示例代码,以及您打算解决的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.