我有一个对象:
ExampleClass ex = new ExampleClass();
和:
Type TargetType
我想像这样将 ex 转换为 TargetType 描述的类型:
Object o = (TargetType) ex;
但是当我这样做时,我得到:
The type or namespace name 't' could not be found
那么如何做到这一点呢?我是否遗漏了一些令人讨厌的东西?
更新:
我想获得这样的东西:
public CustomClass MyClassOuter
{
get
{
return (CustomClass) otherClass;
}
}
private otherClass;
因为我会有很多这样的属性,所以我想这样做:
public CustomClass MyClassOuter
{
get
{
return (GetThisPropertyType()) otherClass;
}
}
private SomeOtherTypeClass otherClass;
上下文:
通常在我的类里面下文中,我需要创建许多属性。并且在每一个中都将类型转换替换为属性(property)的类型。它对我来说似乎没有意义(在我的上下文中),因为我知道返回类型是什么,我想编写某种代码来为我进行转换。也许这是泛型的情况,我还不知道。
就好像我可以在这个属性中确保我得到了正确的对象和正确的类型,并且我 100% 能够将它转换为属性类型。
我只需要这样做,这样我就不需要在每个属性中指定它必须“将值转换为 CustomClass”,我想做一些类似“将值转换为与此属性相同的类”的事情".
例如:
class MYBaseClass
{
protected List<Object> MyInternalObjects;
}
class MyClass
{
public SpecialClass MyVeryOwnSpecialObject
{
get
{
return (SpecialClass) MyInteralObjects["MyVeryOwnSpecialObject"];
}
}
}
好吧——我可以像上面这样创建很多属性——但是有两个问题:
1) 我需要在 MyInternalObjects 上指定对象名称,但它与属性名称相同。我用 System.Reflection.MethodBase.GetCurrentMethod().Name 解决了这个问题。
2) 在每个属性中,我需要将对象从 MyInternalObjects 转换为不同的类型。例如在 MyVeryOwnSpecialObject 中 - 到 SpecialClass。它始终与属性属于同一类。
这就是为什么我想做这样的事情:
class MYBaseClass
{
protected List<Object> MyInternalObjects;
}
class MyClass
{
public SpecialClass MyVeryOwnSpecialObject
{
get
{
return (GetPropertyType()) MyInteralObjects[System.Reflection.MethodBase.GetCurrentMethod().Name];
}
}
}
现在担心:好的,为什么?因为在我的应用程序中,我将拥有安全类型等 (intellisense) 的所有好处。
第二个:但是现在你会在这个地方失去类型安全?没有。因为我非常确定我的类型对象在列表中。
最佳答案
Object o = (TargetType) ex;
此代码无用。您可能在右侧有一个类型,但它仍然只是左侧的一个对象。您不能像这样使用特定于 TargetType 的功能。
这是调用给定类型的未知对象的方法的方法:
object myObject = new UnknownType();
Type t = typeof(UnknownType); // myObject.GetType() would also work
MethodInfo sayHelloMethod = t.GetMethod("SayHello");
sayHelloMethod.Invoke(myObject, null);
使用这个 UnknownType 类:
class UnknownType
{
public void SayHello()
{
Console.WriteLine("Hello world.");
}
}
关于c# - 如何将对象转换为 Type 类描述的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1206148/