我們有以下的類不能隱式轉換「串」到通用型<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.
編譯時間錯誤刪除。但它給運行時錯誤:{「對象引用未設置爲對象的實例。」} –
沒有工作。當我嘗試 –
@ user1043788是的,如果你試圖在'FUND_CITY'上爲'PropertyValue'賦值而不初始化'BE'對象上的'FUND_CITY'屬性(它是一個空引用),就會發生這種情況。在「BE」類型的初始化程序中執行此操作,或者可以使用其中一個已發佈的替代示例,如果您決定不實施@leppie建議的隱式操作符設計更改,則建議使用隱式類型示例。 –