开发者

generic algorithm to convert the return values of the System.Data.DataRow Indexer

开发者 https://www.devze.com 2022-12-09 18:27 出处:网络
i am trying to write a function that will make DataRow[column] return nullable typed data. for example:

i am trying to write a function that will make DataRow[column] return nullable typed data. for example: if i have a property

int? iValue { get; set; }

and the DataRow["ID"] will have the int ID in the Database i want to make a wrapper function that will check if the value of the DataRow["ID"] is DBnull and set the iValue to null. and so on for the rest of the datatypes. i wrote the following function

public static v开发者_如何学Gooid CDB<T>(ref T tData, object objDBDataItem)
{
    if (objDBDataItem.GetType().FullName == "System.DBNull")
        tData = default(T);
    tData = (T)objDBDataItem;
}

to call the function i do the following

CDB(ref iValue , DataRow["ID"]);

this should initialize the value of iValue to the integer value of DataRow["ID"] or null if the value in the DB is null. the problem is that this code dont work because i am not allowed to pass proprities as reference. but the idea is that i dont want to call the function as

iValue = CDB<int>(DataRow["ID"]);

so far i was able to make the function work if i change it to be called in the format of

iValue = CDB(iValue, DataRow["ID"]);

but i dont like the idea that i need to repeat iValue (one time to get the Type and one time so that i assign the return value to it.

any suggesions?


One option is to pass a delegate into your function:

public static void CDB<T>(object objDBDataItem, Action<T> setter)
{
    T data;
    if (objDBDataItem is System.DBNull)
        tData = default(T);
    else
        tData = (T)objDBDataItem;

    setter(data);
}

And call it like this:

CDB(DataRow["ID"], (int? i) => iValue = i);

It's also worth pointing out that the logic you describe to hide DBNull is already provided by System.Data.DataRowExtensions.Field:

iValue = DataRow.Field<int?>("ID");

Out of curiosity, why don't you like assigning iValue this way?

0

精彩评论

暂无评论...
验证码 换一张
取 消