[英]Can't access base properties in derived class (C#)
我在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;
}
}
我只包含了一個屬性和一種方法來演示我的問題,但是還有更多的聲明方式相同...
發生的是,當我創建一個新的CellSection時,如下所示:
CellSection<TextInput> section1 = new CellSection<TextInput>();
section1.Title = "New Title"; //This line is not allowed
我不允許訪問Title屬性...
錯誤消息: CellSection<TextInput>' does not contain a definition for 'Title'
通過將以下代碼添加到CellSection<T>
類中,我已經能夠訪問它:
public string Title
{
get { return base.Title; }
set { base.Title = value; }
}
但這似乎是該死的不必要和多余的...必須有另一種方式...
我GetInputType()
的另一個問題是不允許覆蓋虛擬方法GetInputType()
,它也在上面的代碼中,但這是我所談論的這一行:
public override IInputType GetInputType()
{
return InputType;
}
錯誤消息: 'CellSection<T>.GetInputType()': no suitable method found to override
最終的問題是,當我來自不同的類/文件時,嘗試將CellSection<T>
引用/ CellSection<T>
到ICellSection
(由基類CommonCell
)
List<ICellSection> Sections = new List<ICellSection> { section1, section2 };
我收到不允許的錯誤消息。
錯誤消息: Argument 1: cannot convert from 'CellSection<TextInput>' to 'ICellSection'
我不確定這一點,因為我不知道它是否可能(無法找到示例),但是問題1和2我只是不明白為什么它們不起作用,因為它們看起來很簡單向前...
每位客戶支持員工:
“你試過把它關掉再打開嗎?”
我:
“該死...是的,是的,我已將其關閉然后再打開”
原來,這個問題是Visual Studio或Xamarin錯誤。 我刪除了所有相關文件並再次添加了它們(將相同的舊代碼復制並粘貼到新文件中)。 繁榮! 現在一切都已正確繼承。 我不知道是什么引起了這個問題,因為我認為這是.projitems文件中的參考問題,但是對該文件基本上沒有任何更改(在git中檢查幾行切換位置,僅此而已)。
如果將來還有其他人遇到相同或類似的問題:在遇到此問題時,我多次重新啟動了Visual Studio。 遇到此問題時,我至少重啟了計算機一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.