接口引用如何能够调用子类方法。
在下面的示例中,接口引用如何访问测试类对象?
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());
}
Run Code Online (Sandbox Code Playgroud)
-1。
这条线
Console.WriteLine((t as Test).sub());
t将别名为type 的任何内容强制转换Test。
您知道它t可以转换为,因为您为其Test分配了一个实例Test
ITest t = new Test();
Run Code Online (Sandbox Code Playgroud)
请注意,如果 的类型t无法转换为Test,
t as Test
Run Code Online (Sandbox Code Playgroud)
将计算为 null,并且对 .sub() 的后续调用将导致 NullReferenceException。
虽然这很少是一个好的设计选择,但你可以这样做
if (t is Test)
{
Console.WriteLine(((Test)t).sub());
}
else
{
Console.WriteLine("t cannot be converted to type Test");
}
Run Code Online (Sandbox Code Playgroud)
或者替代地
Test myTest = t as Test;
if (myTest != null)
{
Console.WriteLine(myTest.sub());
}
else
{
Console.WriteLine("t cannot be converted to type Test");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1842 次 |
| 最近记录: |