webForumDet fria alternativet

Returnera värde med typ?

.NETur .NET

4 svar · 640 visningar · startad av Jesper T

Medlem sedan nov. 20017 144 inlägg
Frågan#1

Tänker mig en funktion som denna:

private object checkNull(object objVal, System.Type _type) 
{ 
    if (!object.ReferenceEquals(objVal, System.DBNull.Value)) { 
        return (_type)objVal; 
    } 
    else { 
        return (_type)0; 
    } 
} 

string str = checkNull("Hej", string);
decimal dec = checkNull(0.5855, decimal);

Men jag kanske är fel ute, denna funkar ju inte i alla fall.

Medlem sedan dec. 19996 721 inlägg
#2
private T checkDbNull<T>(T objVal, T ifnull) 
{ 
    if (!object.ReferenceEquals(objVal, System.DBNull.Value)) { 
        return objVal; 
    } 
    else { 
        return ifnull; 
    } 
} 

string str = checkNull<string>("Hej", "0");
decimal dec = checkNull<decimal>(0.5855, 0);
Medlem sedan nov. 20017 144 inlägg
#3

Jag får felet: "Conversion from type 'DBNull' to type 'String' is not valid"

Medlem sedan okt. 20041 556 inlägg
#4
private T checkDbNull<T>(object objVal, T ifnull) 
{ 
    if (!object.ReferenceEquals(objVal, System.DBNull.Value)) { 
        return objVal; 
    } 
    else { 
        return ifnull; 
    } 
}
Medlem sedan dec. 19996 721 inlägg
#5

return (T)objVal

i så fall

143 ms totalt · 3 externa anrop · v20260731065814-full.25f56b17
0 ms — hämta forumlista (cache)
0 ms — hämta statistik (cache)
140 ms — hämta tråd, inlägg och bilagor (db)