You can use the dynamic
keyword for just this purpose. See here for the programming guide.
I hope this helps.
Вопрос
I am using the following linq to parse a dataset that I have returned:
row.Field<long?>("id").HasValue == false &&
The problem I'm running into is that when the dataset is obtained from Sql Server, the field needs to be parsed with <int?>
and when it's obtained from Oracle, it needs to be parsed as <long?>
. Is there a way to create a variable that I can pass in to the .Field method to dynamically set this data type? I'd like to have something like this:
Type T = IsSqlServer ? typeof(int?) : typeof(long?);
....
row.Field<T>("id").HasValue == false &&
Thanks in advance!
Решение 2
You can use the dynamic
keyword for just this purpose. See here for the programming guide.
I hope this helps.
Другие советы
You could either use reflection (not recommended) or just use the ternary operator:
!(IsSqlServer ? row.Field<int?>("id").HasValue : row.Field<long?>("id").HasValue)
Here's an extension method:
public static class DataRowHelpers
{
private static readonly Dictionary<Type, MethodInfo> FieldSpecialized = new Dictionary<Type, MethodInfo>();
public static bool FieldHasValue(this DataRow row, Type type, string column)
{
MethodInfo fieldSpecialized;
if(!FieldSpecialized.TryGetValue(type, out fieldSpecialized))
{
var extensions = typeof(DataRowExtensions);
var fieldGeneric = extensions.GetMethod("Field",
new[] { typeof(DataRow), typeof(string) });
fieldSpecialized = fieldGeneric.MakeGenericMethod(type);
FieldSpecialized.Add(type, fieldSpecialized);
}
return fieldSpecialized.Invoke(null, new object[] { row, column }) != null;
}
}
Usage:
var type = IsSqlServer ? typeof(int?) : typeof(long?);
var predicate = row.FieldHasValue(type, "id");