English 中文(简体)
采用接口方法使用母异构体的儿童类别时采用接口
原标题:Implementation of interface when using child class of a parent class in method of interface
  • 时间:2010-04-06 21:36:58
  •  标签:
  • c#

我没有机会进入我的发展中环境,但在我写以下文字时:

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) 
    { 
    }
}

Note for Charles: You can use generic to get strongly typed method, otherwise you do not need to change signature of the method in child class, but just call it with any child of HtmlControl

问题回答

在接口中,可以通过 任何>的代码>HtmlControl。 页: 1 范围只有<代码>HtmlTextArea,因此不能通过,你不能这样做:

说明这一理由的例子:

var btn = new HtmlButton(); //inherits from HtmlControl as well

IExample obj = new Example();
obj.Test(btn); //Uh oh, this *should* take any HtmlControl




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签