Jus*_*tin 1 c# reflection casting
我的方法收到一个object. 我确定它是一个使用反射的二维元组Tuple<,>。我不知道编译时二维元组的通用类型。如何访问元组中的字段?我假设我必须转换为底层元组类型,但我不知道如何转换。
public static class Foo
{
private static Bar(object inputObject, Type inputType)
{
if (inputType.IsOrImplementsType(typeof(Tuple<,>)))
{
Type keyType = inputType.GenericTypeArguments[0];
Type valueType = inputType.GenericTypeArguments[1];
// Now how can I cast to the concrete type of Tuple<keyType, valueType> to access the tuple Item1 and Item2 fields?
// Doing this yields : keyType is a variable but is used like a type.
var convertedTuple = inputObject as Tuple<keyType, valueType>;
// now we can access convertedTuple.Item1
}
}
}
Run Code Online (Sandbox Code Playgroud)
System.Reflection在这里使用:只需使用is运算符即可。System.Runtime.CompilerServices.ITuple界面。interface ITupleclass Tuple<...>由和实现struct ValueTuple<...>,这很好,因为这意味着您可以拥有单个代码路径。private static void Bar( object? inputObject )
{
if( inputObject is ITuple tuple && tuple.Length == 2 )
{
Object? value0 = tuple[0];
Object? value1 = tuple[1];
// Do stuff here...
}
}
Run Code Online (Sandbox Code Playgroud)
...但是如果您知道inputObject它始终是元组类型,那么为什么不这样做呢?
// For System.Tuple<T0,T1>:
private static void Bar<T0,T1>( Tuple<T0,T1> inputObject )
{
T0 value0 = inputObject.Item1;
T1 value1 = inputObject.Item2;
// Do stuff here...
}
// For System.ValueTuple<T0,T1>:
private static void Bar<T0,T1>( ValueTuple<T0,T1> inputObject )
{
T0 value0 = inputObject.Item1;
T1 value1 = inputObject.Item2;
// Do stuff here...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |