![](/img/trans.png)
[英]How to use Convert.ChangeType() when conversionType is a nullable int
[英]Convert.ChangeType throwing Invalid Cast Exception for nullable int
如果我在下面調用GetClaimValue方法(其中T是可為null的int),則獲取無效的Cast異常。
private static T GetClaimValue<T>(string claimType, IEnumerable<Claim> claims)
{
var claim = claims.SingleOrDefault(c => c.Type == claimType);
if (claim != null)
return (T) Convert.ChangeType(claim.Value, typeof(T));
return default(T);
}
例如:
GetClaimValue<int?>(IdentityServer.CustomClaimTypes.SupplierId, claims)
有人知道如何處理嗎?
我假設Claim.Value
是Object
類型,並且您在此處進行動態轉換,您無法直接將int
轉換為int?
通過Convert.ChangeType
。
一種選擇是使用Nullable.GetUnderlyingType
,它將檢查這是否為可為空的結構情況,首先通過基礎數據類型進行轉換,然后轉換為T
您還需要處理null
方案。
if (claim != null)
{
var conversionType = typeof(T);
if (Nullable.GetUnderlyingType(conversionType) != null)
{
if (claim.Value == null) //check the null case!
return default(T);
//use conversion to `int` instead if `int?`
conversionType = Nullable.GetUnderlyingType(conversionType);
}
return (T)Convert.ChangeType(claim.Value, conversionType);
}
我無法解釋為什么它會引發異常,但是當我使用Convert.ChangeType
時,我遇到了類似的情況。
嘗試先獲取您傳入的類型的轉換器,然后使用該轉換器進行轉換。 使用此方法可獲得更好的結果。
var converter = TypeDescriptor.GetConverter(typeof(T));
return (T)converter.ConvertFrom(claim.Value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.