[英]C# - Converting object to int without casting
我有一個方法,該方法根據給定的列(數據庫類)返回一種對象。 但是,當我分配對象時,編譯器將引發錯誤,提示它無法將對象類型隱式轉換為int。 如何在不進行轉換的情況下進行轉換?
看起來更好:
this.Id = datum["Id"];
但是現在我必須包含一個強制轉換,這使得代碼不那么干凈,更難編碼:
this.Id = (int)datum["Id"];
這是我的代碼:
public object this[string name]
{
get
{
object result;
if (this.Dictionary.ContainsKey(name))
{
if (this.Dictionary[name] is DBNull)
{
result = null;
}
else if (this.Dictionary[name] is byte && Meta.IsBool(this.Table, name))
{
result = (byte)this.Dictionary[name] > 0;
}
else
{
result = this.Dictionary[name];
}
}
else
{
result = default(object);
}
return result;
}
set
{
if (value is DateTime)
{
if (Meta.IsDate(this.Table, name))
{
value = ((DateTime)value).ToString("yyyy-MM-dd");
}
else if (Meta.IsDateTime(this.Table, name))
{
value = ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
}
}
if (this.Dictionary.ContainsKey(name))
{
this.Dictionary[name] = value;
}
else
{
this.Dictionary.Add(name, value);
}
}
}
您可以將索引器簽名更改為:
public dynamic this[string name]
這將使轉換在執行時動態化。
就個人而言,我更喜歡強制轉換方法。 很明顯,這可能會失敗-您正在告訴編譯器您有不可用的信息。
Dictionary<,>.TryGetValue
,可以利用Dictionary<,>.TryGetValue
和字典索引器的行為來更簡單地編寫代碼:
public object this[string name]
{
get
{
object result;
if (Dictionary.TryGetValue(name, out result))
{
if (result is DBNull)
{
result = null;
}
else if (result is byte && Meta.IsBool(this.Table, name))
{
result = (byte) result > 0;
}
}
return result;
}
set
{
// TODO: Byte/bool conversions?
if (value is DateTime)
{
// Note use of invariant culture here. You almost certainly
// want this, given the format you're using. Preferably,
// avoid the string conversions entirely, but...
DateTime dateTime = (DateTime) value;
if (Meta.IsDate(this.Table, name))
{
value = dateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
else if (Meta.IsDateTime(this.Table, name))
{
value = dateTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
}
}
Dictionary[name] = value;
}
}
使用類Convert
:
Convert.ToInt32(datum["Id"]);
如果您不需要在代碼中聲明要從object
為int
,那么編程語言將無法幫助您避免錯誤。
C#確實具有一項功能,您可以關閉對特定變量的靜態類型檢查:使索引器返回dynamic
:
public dynamic this[string name]
然后您可以說:
int n = datum["Id"];
但不利的一面是,直到運行時,您才能發現這是否正確。
您可以執行擴展方法。
創建一個這樣的類。
public static class ExtensionMethods
{
public static int AsInt(this object obj)
{
return (int)obj; // add additional code checks here
}
}
然后,在您的實際代碼中,您所需要做的就是像這樣調用擴展方法。
this.Id = datum["Id"].AsInt();
我知道這看起來與AsInt
相同,但是它發生在方法調用AsInt
下面,並且您的代碼更加AsInt
易讀,因為AsInt
流暢且確定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.