对于声明为该类实现的接口之一的类型的变量,如何在继承类中使类的属性可用?
到目前为止我所做的是MyAbstract
使用关键字MustInherit 创建一个抽象类,在继承类中MyInheritingClass
我添加了继承,然后是抽象类的名称.现在这一切都很好,但是在我的继承类中,如果我在该类上创建一个接口MyInterface
并在我的代码中的其他地方使用该接口,那么我发现我无法从我的抽象类中看到属性,在那个声明的变量上接口.
我在这里做错了什么,或者我还需要做些什么吗?
一个例子如下:
Public MustInherit Class MyAbstract
Private _myString as String
Public Property CommonString as String
Get
Return _myString
End Get
Set (value as String)
_myString = value
End Set
End Property
End Class
Public Class MyInheritingClass
Inherits MyAbstract
Implements MyInterface
Sub MySub(myParameter As MyInterface)
myParameter.CommonString = "abc" ' compiler error - CommonString is not a member of MyInterface.
End Sub
'Other properties and methods go here!'
End Class
Run Code Online (Sandbox Code Playgroud)
所以,这就是我正在做的事情,但是当我使用时MyInterface
,我看不到我的抽象类的属性!
除非我完全误解了你的问题,否则我不确定为什么你会对这种行为感到困惑.它不仅应该如何工作,而且它也是如何在c#中工作的.例如:
class Program
{
private abstract class MyAbstract
{
private string _myString;
public string CommonString
{
get { return _myString; }
set { _myString = value; }
}
}
private interface MyInterface
{
string UncommonString { get; set; }
}
private class MyInheritedClass : MyAbstract, MyInterface
{
private string _uncommonString;
public string UncommonString
{
get { return _uncommonString; }
set { _uncommonString = value; }
}
}
static void Main(string[] args)
{
MyInterface test = new MyInheritedClass();
string compile = test.UncommonString;
string doesntCompile = test.CommonString; // This line fails to compile
}
}
Run Code Online (Sandbox Code Playgroud)
通过任何接口或基类访问对象时,您将只能访问该接口或基类公开的成员.如果需要访问其成员MyAbstract
,则需要将对象强制转换为MyAbstract
或MyInheritedClass
.这两种语言都是如此.