2011-11-16 48 views
2

而是寫作任何人都知道我可以如何獲得用於c#類型的FCL樣式初始化語法?

int i = new int(); 
i = 7; 

可以寫

int i = 7; 

有沒有一種方法可以讓我得到初始化的這種風格對我自己的類型?

MyType mt = xyz; 
+0

。 –

+1

這是什麼'xyz'? –

+0

沒什麼。但是,舉個例子,我想寫一個自定義字符串類 - String2。我可以設計它,使它初始化爲String2 s2 =「yo」。或者我堅持讓它看起來像String2 s2 =新的String2(「喲」)或一些這樣的詳細程度。我只是尋找簡潔的FCL原語在我自己的類型中使用。 – endlessnameless

回答

2

您可以最接近的是通過在您的類型上創建隱式轉換。例如:

public class Unit 
{ 
    public static implicit operator Unit(string val) 
    { 
    return Unit.Parse(val); 
    } 

    public static Unit Parse(string unitString) 
    { 
    // parsing magic goes here 
    } 
} 

這將使您能夠做這樣的事情:

Unit width = "150px"; 
var width = Unit.Parse("150px"); // equivalent to previous line 

請注意,你不能引入新的語法;這將是不可能來實現:

Unit width = 150px; 

因爲150px並不代表一個有效的值類型。

請注意,隱式轉換可能會讓您以奇怪的方式陷入困境,因此請不要這樣做。只支持向你真正需要的類型進行隱式轉換。

或者,如果您正在使用C#編譯器3.5或多達你也可以使用內聯初始化是更冗長,但也更加明確:

Unit with = new { Value=150, UnitType=Units.Pixel }; 
0

簡短的回答是「不,你不能。」你總是會在某個地方隱藏new

在特定情況下,你可以做一些技巧與隱式轉換是這樣的:

class String2 { 
    private readonly string WrappedString; 

    public String2(string wrappedString) { 
     this.WrappedString = "my modified " + wrappedString ; 
    } 

    public override string ToString() { 
     return this.WrappedString; 
    } 

    // the "magic" is here: the string you assign to String2 gets implicitly 
    // converted to a String2 
    public static implicit operator String2(string wrappedString) { 
     return new String2(wrappedString); 
    } 
} 

,使您能夠做到:

String2 test = "test"; 
Console.WriteLine(test.ToString()); // writes: "my modified test" to the Console 

,但你的「新」藏在隱無論如何轉換。

這可能是更普遍和土地你不能從你想要的語法太遠另一種方法是通過擴展方法:

static class StringExtensions { 
     public static String2 ToString2(this string that) {return new String2(that);} 
    } 

與範圍,你可以這樣做:

var test2="anothertest".ToString2(); 
+0

謝謝。隱式轉換是什麼MSFT用來允許快速初始化爲int /字節/字符串等? – endlessnameless

+1

不,不是。原始類型,如int/byte/string,得到編譯器的特殊處理。 –

0

對於評論中的具體示例,您可以將implicit conversion operator添加到該類型中。

請注意,通常不建議這樣做,因爲它會使您的代碼不易讀。例如,像String2 s2 = new String2("yo")這樣的東西完全明確發生了什麼;不像String2 s2 = "yo"這樣的東西。

String2 s2 = "yo"; 

// ... 

public sealed class String2 
{ 
    public readonly string _value; 
    public string Value { get { return _value; } } 

    public String2(string value) 
    { 
     _value = value; 
    } 

    public override string ToString() 
    { 
     return Value; 
    } 

    public static implicit operator String2(string value) 
    { 
     return new String2(value); 
    } 
} 
+0

這是rad!我喜歡。我不介意它不那麼「可讀」,因爲它是爲我自己的代碼而不是庫。什麼是可讀的呢?除了微軟允許它工作以外的事情有效嗎?就我個人而言,我很困惑爲什麼某些類型可以用語法糖初始化,而其他類型則不能。你必須深入研究框架來計算int和string是如何用語法糖來實現的,但它並沒有被明確給我們。對於我自己的類型,如果我寫它,它對我來說是明確的。謝謝! – endlessnameless

相關問題