C#4继承和可选参数 [英] C# 4 Inheritance and Optional Arguments

查看:67
本文介绍了C#4继承和可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

快速提问:

Hi All,

Quick question:

public class A<br />
{<br />
public virtual void F() {}<br />
}<br />
public class B : A<br />
{<br />
public virtual void F(int i=10) {}<br />
}<br />
<br />
A a = new B();<br />
a.F();



哪个"F"被调用-还是不编译,警告模棱两可?还是这是个迷惑的问题?



Which ''F'' gets called - or does it not compile, warning about an ambiguity? Or is this a dozy question?

推荐答案

我在家里尝试过代码,答案是您的代码可以编译,并且没有歧义!如果您改为这样做:


I tried the code at home, the answer is your code will compile, and there is no ambiguity! If you''d done this instead:


public class B : A
{
  public <big>override</big> void F(int i=10) {}
}



它会失败,不是由于模棱两可,而是因为实际上,类A没有要覆盖的public void F(int i).

您的代码将在类A中调用方法F.附带说明一下,就编译器而言,即使可以调用B.F(),它也不存在.因此,如果要覆盖,则只需要有一个虚拟的A.F(int)而不是一个A.F()

我已经更新了我的文章(而不是继续的无耻插件!),以包括您问题的影响!
命名和可选参数 [



It would have failed, not due to ambiguousness but because, in effect, class A doesn''t have a public void F(int i) to override.

Your code will call method F in class A. As a side note, as far as the compiler is concerned B.F() doesn''t exist, even though you can call it. So if you were to override, you only need to have a virtual A.F(int) and not a A.F()

I''ve updating my article (not the continued shameless plug!), to include the fallout from your question!
Named and Optional Arguments[^]


因为它无法确定您所使用的F版本试图打电话.想一想.

您有F()-一种没有参数的方法,和F(int i=10)-一种可以无参数调用的方法.

如果调用F(),编译器应选择哪一个?它们本质上是相同的.但是,如果调用F(10),它将知道选择哪个版本,但是此时,重载是无效的,因为尽管使用了默认参数,但必须使用参数调用它才能使用它.

最好的选择是移动两者的结合并保留您的可选参数.
Because it can''t determine which version of F you''re trying to call. Think about it.

You have F() - a method with no parameters, and F(int i=10) - a method that can be CALLED with no parameters.

If you call F(), which one should the compiler chose? They''re essentially the same. However, if you call F(10) it knows which version to pick, but at that point, your overload is ineffectual because despite the default parameter because you must call it with a parameter in order to use it.

Your best bet is to move the combine the two and keep your optional parameter.


公共类A
{
公共虚拟虚空F()
{
Console.WriteLine("A's F()");
}
}
公众B级:A
{
公共虚拟虚空F(int i = 10)
{
Console.WriteLine("B's F()");
}
}

班级计划
{
静态void Main(String [] args)
{
A a = new B();
a.F();
}

答案:A的F()
public class A
{
public virtual void F()
{
Console.WriteLine("A''s F()");
}
}
public class B : A
{
public virtual void F(int i=10)
{
Console.WriteLine("B''s F()");
}
}

Class Program
{
static void Main(String[]args)
{
A a = new B();
a.F();
}

Answer:A''s F()


这篇关于C#4继承和可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆