2014-05-21 84 views
2

我愿做这样的事情在C#:如何在不使用新的情况下直接分配?

Foo test = "string"; 

而且现在的对象应该被初始化。我怎样才能做到这一点?我无法让它工作,但我知道这是可能的。

+0

答案在这里:[在C#中重载赋值运算符](http://stackoverflow.com/a/4537848/754376) – vaxo

回答

8

您正在寻找隐式转换运算符。

public class Foo 
{ 
    public string Bar { get; set; } 

    public static implicit operator Foo(string s) 
    { 
     return new Foo() { Bar = s }; 
    } 
} 

然后,你可以这样做:

Foo f = "asdf"; 
Console.WriteLine(f.Bar); // yields => "asdf"; 
0

您可以使用转换操作符隐式:

sealed class Foo 
{ 
    public string Str 
    { 
     get; 
     private set; 
    } 

    Foo() 
    { 
    } 

    public static implicit operator Foo(string str) 
    { 
     return new Foo 
     { 
      Str = str 
     }; 
    } 
} 

然后,你可以做Foo test = "string";

+1

+1,但你应该修复你的答案中的语法错误。 ('Str'不存在) – Stijn

相关问题