我在C#/Xamarin.Forms中遇到了继承/多态的问题。有很多事情我认为我应该可以做到,但实际上我不能,从我的理解来看,似乎我没有正确地继承,所以首先要做的是:
声明
public abstract partial class CommonCell : ContentView, ICellSection
{
public static readonly BindableProperty TitleProperty = BindableProperty.Create("Title", typeof(string), typeof(CommonCell), default(string));
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public CommonCell()
: base()
{
}
public virtual IInputType GetInputType()
{
throw new NotImplementedException();
}
}
在同一个文件中,我还声明了这个派生类:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CellSection<T>: CommonCell where T : View, IInputType
{
private T _inputType;
public T InputType
{
get { return _inputType; }
set { _inputType = value; } //plus more stuff here
}
public CellSection ()
:base()
{
//Layout Initialization
}
public override IInputType GetInputType() //I get an error here (Problem 2)
{
return InputType;
}
}
我将只展示一个属性和一个方法,以演示我的问题,但是有许多类似的声明方式...
问题1
当我创建一个新的CellSection时,发生的情况是这样的:
CellSection<TextInput> section1 = new CellSection<TextInput>();
section1.Title = "New Title"; //This line is not allowed
我无法访问Title属性...
错误信息:CellSection<TextInput>'未包含'Title'的定义
我通过在CellSection<T>
类中添加以下代码来访问它:
public string Title
{
get { return base.Title; }
set { base.Title = value; }
}
但这似乎是不必要和冗余的...肯定有其他方法...
问题2
另一个问题是我不能覆盖虚拟方法GetInputType()
,它也出现在上面的代码中,但这就是我所说的那一行:
public override IInputType GetInputType()
{
return InputType;
}
错误信息:
'CellSection<T>.GetInputType()': 没有适合的方法可以重写
问题3
最后一个问题是,当我试图从不同的类/文件中引用/转换CellSection<T>
为ICellSection
(由基类CommonCell
实现)时,出现了问题。
List<ICellSection> Sections = new List<ICellSection> { section1, section2 };
我遇到了一个错误,它是不允许的。
错误信息:参数 1:无法将类型为“CellSection<TextInput>”的对象强制转换为类型“ICellSection”
对于这个问题,我更加不确定是否可能(找不到相关示例),但是问题 1 和 2 我就是不明白为什么不能工作,因为它们似乎非常简单直接...
CommonCell
是一个抽象类,为什么要实现一个只会抛出NotImplementedException
的虚方法呢?为什么不直接声明该方法为抽象方法public abstract IInputType GetInputType();
呢? - Adwaenyth