简体   繁体   English

如何将方法结果作为参数传递给C#中的基类构造函数?

[英]How to pass method result as parameter to base class constructor in C#?

I've trying to achieve something like this: 我正在努力实现以下目标:

class App {
    static void Main(string[] args) {

        System.Console.WriteLine(new Test("abc")); //output: 'abc'
        System.Console.ReadLine();
    }
}

I can do this passing by an variable: 我可以通过一个变量来做到这一点:

   class Test {
        public static string str; 
        public Test (string input) { str = input; }

        public override string ToString() {
                return str; 
        }
    }

works fine. 工作正常。 But, my desire is do something as: 但是,我的愿望是:

class Test {
        public static string input;
        public Test (out input) { }

        public override string ToString() {
                return input;
        }
    }

  System.Console.WriteLine(new Test("abc test")); //abc test

Don't works. 不行 How I do this? 我该怎么做? Thanks,advanced. 谢谢,谢谢。

You can't. 你不能 The variable approach is exactly the correct way, although the variable shouldn't be declared static, and shouldn't be a public field. 变量方法是正确的方法,尽管不应将变量声明为静态变量,也不应将其设为公共字段。

class Test {
    public string Input {get;set;}
    public Test (string input) { Input = input; }

    public override string ToString() {
            return Input;
    }
}

I have an impression that you're not entirely understand what out keyword means. 我的印象是您并不完全了解out关键字的含义。 Essentially when you're writing something like void MyMethod(out string var) it means you want to return some value from method, not pass it into method. 本质上,当您编写诸如void MyMethod(out string var)之类的东西时,这意味着您想方法中返回一些值,而不是将其传递方法。 For example there's bool Int32.TryParse(string s, out int result) . 例如,有一个bool Int32.TryParse(string s, out int result) It parses string s, returns if parse was successful and places parsed number to result. 它解析字符串s,如果解析成功则返回,并将解析后的数字放入结果中。 Thus, to correctly use out you should have real variable at the calling place. 因此,要正确使用完out您应该在调用位置使用实数变量。 So you can't write Int32.Parse("10", 0) because this method can't assign result of 10 to 0. It needs real variable, like that: 因此,您无法编写Int32.Parse("10", 0)因为此方法无法将10的结果赋给0。它需要像这样的实数变量:

int result;
bool success = Int32.TryParse("10", out result);

So, your desire is somewhat else - it is not in line with language designer's intentions for out :) 所以,你的愿望是有点别的-这是不符合语言设计者的用心线路out :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM