[英]C# Return Zero in Corresponding Input Type
我想要一個執行此操作的函數:
private static dynamic Zero(Type T)
{
if (T == typeof(Decimal))
{
return Decimal.Zero;
}
else if (T == typeof(Double))
{
return new Double();
}
else if (T == typeof(Int64))
{
return new Int64();
}
...
}
但對於所有類型。 我想避免編寫其他if語句。 還有其他方法嗎? 我正在使用C#4.0。
return default(T);
對於值類型,默認構造函數將起作用。
if(T.IsValueType()) return Activator.CreateInstance(T);
然后,您可以做其他事情,例如測試類型的Zero方法,如果是,則調用它。
這里不需要dynamic
:
private static T Zero<T>()
{
return default(T);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.