2011-11-13 36 views
0

我們有以下的類不能隱式轉換「串」到通用型<T>

public class MyPropertyBase 
{ 
    public int StartOffset { get; set; } 
    public int EndOffset { get; set; } 
} 

public class MyProperty<T> : MyPropertyBase 
{ 
    public MyProperty(T propertyValue) 
    { 
     PropertyValue = propertyValue; 
    } 

    public T PropertyValue { get; set; } 
} 

class BE 
{ 
    public MyProperty<string> FUND_CITY { get; set; } 

    public MyProperty<int> SomeOtherProperty { get; set; } 

    public List<MyPropertyBase> MyDataPoints { get; set; } 
} 

當我創建的BE實例作爲objBE並指定objBE.FUND_CITY="Some Value"它給人的錯誤:

"Can't convert "string" to MyProperty.

回答

1

這是正確的。 FUND_CITY不是string,而是MyProperty<string>類型。你需要做的事:

objBE.FUND_CITY = new MyProperty<string>("Some Value"). 

或者,如果你有一個參數的構造函數,你可以這樣做:

objBE.FUND_CITY = new MyProperty<string>(); 
objBE.FUND_CITY.PropertyValue = "Some Value"; 
0

隨着你目前的設計,你需要寫

objBE.FUND_CITY.PropertyValue = "Some Value"; 

這是因爲BEFUND_CITY財產不是string,它是MyProperty<string>,它本身具有名爲PropertyValue的財產。

3

這是因爲BE實例objBEFUND_CITY成員是MyProperty<string>型的,而不是string所以您要值分配給了錯誤的類型。

你可以這樣做:

objBE.FUND_CITY.PropertyValue = "Some Value"; 

,並有可能生成你正在尋找其他方式來直接設定成員,你可以做類似下面的結果。

objBE.FUND_CITY = new MyProperty<string>("Some Value"); 

,或者如果你想使用隱式類型..

objBE.FUND_CITY = new MyProperty("Some Value"); 
+0

編譯時間錯誤刪除。但它給運行時錯誤:{「對象引用未設置爲對象的實例。」} –

+0

沒有工作。當我嘗試 –

+0

@ user1043788是的,如果你試圖在'FUND_CITY'上爲'PropertyValue'賦值而不初始化'BE'對象上的'FUND_CITY'屬性(它是一個空引用),就會發生這種情況。在「BE」類型的初始化程序中執行此操作,或者可以使用其中一個已發佈的替代示例,如果您決定不實施@leppie建議的隱式操作符設計更改,則建議使用隱式類型示例。 –

1

嘗試objBE.FundCity =新myProperty的( 「someValue中」);

3

如果您需要該語法,則需要隱式轉換。

實施例:

public class MyProperty<T> : MyPropertyBase 
{ 
    public MyProperty(T propertyValue) 
    { 
     PropertyValue = propertyValue; 
    } 

    public T PropertyValue { get; set; } 

    public static implicit operator MyProperty<T>(T t) 
    { 
     return new MyProperty(t); 
    } 
} 
+2

很棒的建議! –

+0

衷心感謝。有效!。偉大的建議! –

+0

這絕對是解決這個問題的更有效的方法。我也想指出,你可以創建一個從「MyProperty」類型到類型T的隱式轉換,這也可以讓你從屬性返回賦值。當你不需要任何特殊功能時,這本質上就使得該屬性透明。 –

相關問題