如何将一个对象转换成它的类型? [英] How to cast an object into its type?
问题描述
如何将对象(类型为Object)转换为实型?
How to cast an object (of type Object) into its real type?
我需要做这样的事情
Myobject [i] += Myobject [j];
Myobject的类型是Object.Myobject [i]和myobject [j]将始终是同一类型.
Myobject's type is Object. Myobject [i] and myobject [j] will always be of same type.
Myobject [i] .Gettype()会给我类型...但是我如何实际将对象转换为该类型以执行'+'运算符
Myobject[i].Gettype() would give me the type... but how would i actually cast the object into that type to perform the '+' operator
推荐答案
我假设为您的自定义类型( MyType
中的定义了加法( +
)运算符这个例子).
I'm assuming the addition (+
) operator is defined for your custom type (MyType
in this example).
如果是这样,您只需要转换分配的LHS和RHS.这是必需的,因为两个操作数在编译时必须为 known 类型,以便选择正确的运算符重载.这是静态语言所必需的,尽管动态语言(可能是C#4.0)可以解决此问题.
If so, you simply need to cast the LHS and RHS of the assignment. This is required because both operands must be of known types at compile-time in order to choose the correct operator overload. This is something required by static languages, though dynamic languages (possibly C# 4.0) may resolve this.
((MyType)Myobject[i]) += (MyType)Myobject[j];
更新:
一些反射魔术可以在C#2.0/3.0中解决此问题(缺少动态类型).
Some reflection magic can get around this problem in C# 2.0/3.0 (with lack of dynamic typing).
public static object Add(object a, object b)
{
var type = a.GetType();
if (type != b.GetType())
throw new ArgumentException("Operands are not of the same type.");
var op = type.GetMethod("op_Addition", BindingFlags.Static | BindingFlags.Public);
return op.Invoke(null, new object[] { a, b });
}
请注意,这仅适用于非原始类型.对于诸如 int
, float
等的原始类型,您将需要在该类型上添加一个switch语句,以手动转换操作数并应用加法运算符.这是因为运算符重载实际上不是为原始类型定义的,而是内置在CLR中的.
Note that this only works for non-primitive types. For primitive types such as int
, float
, etc., you would need to add a switch statement on the type that manually cast the operands and applied the addition operator. This is because operator overloads aren't actually defined for primitive types, but rather built in to the CLR.
无论如何,希望能解决您的问题.
Anyway, hope that solves your problem.
这篇关于如何将一个对象转换成它的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!