【问题标题】:c# private and overload functions [duplicate]c#私有和重载函数[重复]
【发布时间】:2014-09-03 23:43:46
【问题描述】:

为什么MainWindow/this.ab 被隐藏了,看不到了?我想应该在mainWindows 中看到私人信息。

如果我把return 没有放在方法的末尾,C# 似乎会抛出错误Not all code return path value

c#可以同时返回string和void吗?如果我错了,更好的代码是什么?在 PHP 中,代码很容易工作。我需要知道它如何在 C# 中工作。

public static string a(string type,string a)
{
  return MainWindow.ab(type, a);
}
public static void a(string type)
{
  MainWindow.ab(type);
}
private string ab(string type,string a=null)
{
  if (type == "1")
  {
    return "1";
  }
}

【问题讨论】:

  • 这里有很多问题。首先,实例方法(非static)必须通过引用该类的实例来调用。其次,您的非void 方法必须在所有代码路径上返回一个值。如果type != "1"ab 的返回值是多少?我建议你先阅读Methods (C# Programming Guide)

标签: c# wpf


【解决方案1】:

更好的代码是

public static string a(string type,string a)
{
  return MainWindow.ab(type, a);
}
public static string a(string type)
{
  return MainWindow.ab(type);
}
private static string ab(string type,string a=null)
{
  if (type == "1")
    return "1";
  else 
    return null;
}

为什么MainWindow/this.ab是隐藏的,看不到?

因为方法不正确,也不是静态的。

c#可以同时返回string和void吗?

不,您可以返回 null 而不是使用 void

【讨论】:

    【解决方案2】:

    如果你想在你的例子中使用'ab'方法,ab应该在MainWindow中定义如下:

     public static string ab(...)
    

    关于“返回”错误 - 并非所有执行路径都返回一个字符串,例如如果 type != "1",则不提供返回值。

    【讨论】:

    • 我想从外部视图中隐藏它。外部视图只能看到方法/功能。我将其更改为私有或公共,它输出错误“返回 void,返回关键字后面不能跟对象表达式”
    • 您不能在一个函数中同时返回 'void' 和 'string',但您可以使用 'null' 作为另一个答案的建议。关于可见性 - 如果您将其设为“私有”,它将在您定义它的类中可见,受保护的将使其在派生类中也可用,公开 - 对于内部和外部的每个人。让你记住,你真正想要什么:)
    猜你喜欢
    • 2010-10-13
    • 2011-12-11
    • 2012-08-27
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    相关资源
    最近更新 更多