1

我有一个函数正在传递一个字符串和一个数据行。

String 是一个自定义格式化程序。这个想法是这样做的

String.Format(passed_in_String, DataRow("ColumnINeed"))

这样做的原因是此时我们不知道该列包含什么。

但是,如果格式化程序是“{0:MM/dd/yyyy}”并且 DataRow("ColumnINeed") 是一个包含 42 的整数,则 String.Format 将返回:MM/dd/yyyy

在这种情况下,我需要它抛出异常而不是返回废话。

如果对象与格式字符串所期望的不匹配,是否有让 String.Format 抛出异常?

4

2 回答 2

2

You need to become familiar with your data. If you're in a situation where the data could truly be anything at anytime, you're in a bad spot. Frankly, I rather doubt you are in that situation. At least, I'm extremely hopeful you are not.

If it is exceptional for the data in the column to not be a date, then pull it out as a date. Don't pull it out and hope it nicely formats to one, pull it out as one!

DateTime myDate = (DateTime)datarow["MyColumn"]; // C#
Dim myDate As DateTime = CType(datarow("MyColumn"), DateTime) 'VB

Even if you find your data to be stringly typed, immediately parse it. Set the expectation that the value is a date in your code. When it isn't, it will create an exception.

Edit: Chris mentions a good alternate suggestion in the comments. You can also write

DateTime myDate = datarow.Field<DateTime>("MyColumn");

The benefit here is what if the column allowed nulls?

DateTime? myDate = (DateTime?)datarow["MyColumn"]; // C#
Dim myDate = CType(datarow("MyColumn"), DateTime?) 'VB

Here, you may get "Specified Cast Not Valid" if row holds DBNull.

DateTime? myDate = datarow.Field<DateTime?>("MyColumn"); // C#
Dim myDate = datarow.Field(of DateTime?)("MyColumn") 'VB

This alternate handles DBNull appropriately.

于 2011-07-07T01:59:13.990 回答
0

这样做的原因是此时我们不知道该列包含什么。

所以我猜想每次调用函数时,列的数据类型都会有所不同。在这种情况下,也将数据类型与函数一起传递,即,使其成为泛型。

这是一个例子。代替

function myCoolFormatter(string passed_in_String, DataRow drow) { 
    object data = drow("ColumnINeed");
    return string.Format(passed_in_String, data);
}

利用

function myCoolFormatter<T>(string passed_in_String, DataRow drow) { 

    // will raise an exception if ColumnINeed is not of type T
    T data = drow.Field<T>("ColumnINeed");

    return string.Format(passed_in_String, data);
}

然后可以像这样调用您的函数:

var myFormattedString = myCoolFormatter<DateTime>("Date: {0:MM/dd/yyyy}",
                                                  dataRowWithDateTimes);
于 2011-07-07T14:09:26.460 回答