![](/img/trans.png)
[英]Unable to explicitly cast a child class to another child class inside explicit implementation of interface in generic parent base class
[英]Implementation of interface when using child class of a parent class in method of interface
我無權訪問我的開發環境,但在編寫以下內容時:
interface IExample
void Test (HtmlControl ctrl);
class Example : IExample
{
public void Test (HtmlTextArea area) { }
我收到一個錯誤,指出類實現中的方法與接口不匹配-因此這是不可能的。 HtmlTextArea是HtmlControl的子類,這是不可能的嗎? 我嘗試使用.NET 3.5,但是.NET 4.0可能有所不同(我對使用任一框架的任何解決方案都感興趣)。
謝謝
interface IExample<T> where T : HtmlControl
{
void Test (T ctrl) ;
}
public class Example : IExample<HtmlTextArea>
{
public void Test (HtmlTextArea ctrl)
{
}
}
查爾斯的注意事項:可以使用泛型來獲取強類型方法,否則您無需在子類中更改方法的簽名,而只需使用HtmlControl
任何子類調用即可
在界面中,這表示可以傳遞任何 HtmlControl
。 通過說只能傳遞HtmlTextArea
來縮小范圍,所以不,您不能這樣做:)
將此示例圖片化為推理:
var btn = new HtmlButton(); //inherits from HtmlControl as well
IExample obj = new Example();
obj.Test(btn); //Uh oh, this *should* take any HtmlControl
您可以使用泛型來實現 。 給接口一個類型參數,該參數必須限制在HtmlControl及其子級中。 然后,在實現中,您可以使用HtmlControl或后代。 在此示例中,我使用的是HtmlControl,但同時使用HtmlControl和HtmlTextArea調用Test()方法:
public class HtmlControl {}
public class HtmlTextArea : HtmlControl { }
// if you want to only allow HtmlTextArea, use HtmlTextArea
// here instead of HtmlControl
public interface IExample<T> where T : HtmlControl
{
void Test(T ctrl);
}
public class Example : IExample<HtmlControl>
{
public void Test(HtmlControl ctrl) { Console.WriteLine(ctrl.GetType()); }
}
class Program
{
static void Main(string[] args)
{
IExample<HtmlControl> ex = new Example();
ex.Test(new HtmlControl()); // writes: HtmlControl
ex.Test(new HtmlTextArea()); // writes: HtmlTextArea
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.