我寫了這個簡單的實用功能:通用類型化的函數:返回一個非空值
public static T isNull<T>(T? v, T d)
{
return v == null ? d : v.Value;
}
的目的是爲了避免像檢查惱人的任務成員爲空,很普通的在讀LINQ記錄。問題是,它拋出這個錯誤:
The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable< T>'
的錯誤似乎合法的,反正我希望我可以做這樣的事情:的
int? myField = record.myField;
int myValue = isNull(myField, 0);
代替:
int? myField = record.myField;
int myValue = myField == null ? 0 : myField.Value;
我覺得就像我錯過了一些C#的基本知識。有沒有辦法完成我的任務?
出於完整性:http://msdn.microsoft.com/en-us/library/ms173224.aspx –
@LynnCrumbling謝謝,這是一個痛苦在手機上獲取引用 –