开发者

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. 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. For example there's bool Int32.TryParse(string s, out int result). It parses string s, returns if parse was successful and places parsed number to result. Thus, to correctly use out you should have real variable at the calling place. 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:

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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜