提问人:Justin 提问时间:7/6/2023 最后编辑:Heretic MonkeyJustin 更新时间:7/6/2023 访问量:53
如何在 C 语言中将对象转换为使用泛型的类型#
How to cast from object to type which uses generics in C#
问:
我的方法收到一个.我确定它是一个使用反射的 2 维元组。我不知道编译时二维元组的泛型类型。如何从元组访问字段?我假设我必须强制转换为基础元组类型,但我看不到如何。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
}
}
}
答:
6赞
Dai
7/6/2023
#1
- 您不需要在此处使用:只需使用运算符即可。
System.Reflection
is
- 可以使用
System.Runtime.CompilerServices.ITuple
接口。 interface ITuple
由 和 实现,这很好,因为这意味着您可以拥有单个代码路径。class 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...
}
}
...但是,如果您知道总是元组类型,那么为什么不这样做呢?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...
}
评论
MakeGenericMethod
Tuple<...>
ValueTuple<...>
Tuple<...>