【发布时间】:2019-07-22 12:32:48
【问题描述】:
Here's我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
ISampleInterface a = new A();
ISampleInterface b = new B();
a.SampleMethod();
b.SampleMethod();
//Console.WriteLine(a.myValue); // can't do it!! a is not A
Console.WriteLine(a.GetType()); // uhm...
}
}
interface ISampleInterface
{
void SampleMethod();
}
class A : ISampleInterface
{
public double myValue = 10.0;
public void SampleMethod() {
Console.WriteLine("A");
}
}
class B : ISampleInterface
{
public double myValue = 20.0;
public void SampleMethod() {
Console.WriteLine("B");
}
}
}
我通过接口初始化一个类(由类实现)。
显然,无法访问a.myValue,因为正确地Rextester.ISampleInterface 不包含这样的定义。
但如果我询问编译器哪个类型是a,它会输出Rextester.A(我相信不是)。
为什么?更重要的是,a 是哪一类?一种受其接口限制的混合切片类?不知道我会如何定义它......
【问题讨论】:
-
无论你把它施放成什么,实例都是一样的。
-
运行时 != 编译时间
-
您似乎已停止对答案发表评论 - 目前尚不清楚您是否仍然不确定问题,或者您只是在等待决定是否接受。如果您仍然不清楚某些事情,如果我们知道什么会有所帮助。