C# 如何将对象转换为 Type 类描述的类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1206148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:54:05  来源:igfitidea点击:

How to cast object to type described by Type class?

c#.net-3.5castingtypes

提问by Tomasz Smykowski

I have a object:

我有一个对象:

ExampleClass ex = new ExampleClass();

And:

和:

Type TargetType

I would like to cast ex to type described by TargetType like this:

我想将 ex 转换为 TargetType 描述的类型,如下所示:

Object o = (TargetType) ex;

But when I do this I get:

但是当我这样做时,我得到:

The type or namespace name 't' could not be found

找不到类型或命名空间名称“t”

So how to do this? Am I missing something obious here?

那么如何做到这一点呢?我在这里错过了什么令人讨厌的东西吗?

Update:

更新:

I would like to obtain something like this:

我想获得这样的东西:

public CustomClass MyClassOuter
{
   get
   {
        return (CustomClass) otherClass;
   }
}

private otherClass;

And because I will have many properties like this I would like do this:

因为我会有很多这样的属性,所以我想这样做:

public CustomClass MyClassOuter
{
   get
   {
        return (GetThisPropertyType()) otherClass;
   }
}

private SomeOtherTypeClass otherClass;

Context:

语境:

Normally in my context in my class I need to create many properties. And in every one replace casting to the type of property. It does not seem to have sense to me (in my context) because I know what return type is and I would like to write some kind of code that will do the casting for me. Maybe it's case of generics, I don't know yet.

通常在我的班级上下文中,我需要创建许多属性。并且在每一个中都将转换替换为属性类型。这对我来说似乎没有意义(在我的上下文中),因为我知道返回类型是什么,并且我想编写某种代码来为我进行转换。也许这是泛型的情况,我还不知道。

It's like I can assure in this property that I get the right object and in right type and am 100% able to cast it to the property type.

就像我可以在这个属性中保证我得到正确的对象和正确的类型,并且我 100% 能够将它转换为属性类型。

All I need to do this so that I do not need to specify in every one property that it has to "cast value to CustomClass", I would like to do something like "cast value to the same class as this property is".

我只需要这样做,这样我就不需要在每个属性中指定它必须“将值转换为 CustomClass”,我想做类似“将值转换为与此属性相同的类”之类的操作。

For example:

例如:

class MYBaseClass
{
   protected List<Object> MyInternalObjects;
}

class MyClass
{
   public SpecialClass MyVeryOwnSpecialObject
   {
      get
      {
           return (SpecialClass) MyInteralObjects["MyVeryOwnSpecialObject"];
      }
   }
}

And ok - I can make many properties like this one above - but there is 2 problems:

好的 - 我可以制作很多像上面这样的属性 - 但有两个问题:

1) I need to specify name of object on MyInternalObjects but it's the same like property name. This I solved with System.Reflection.MethodBase.GetCurrentMethod().Name.

1)我需要在 MyInternalObjects 上指定对象的名称,但它与属性名称相同。我用 System.Reflection.MethodBase.GetCurrentMethod().Name 解决了这个问题。

2) In every property I need to cast object from MyInternalObjects to different types. In MyVeryOwnSpecialObject for example - to SpecialClass. It's always the same class as the property.

2)在每个属性中,我需要将对象从 MyInternalObjects 转换为不同的类型。例如在 MyVeryOwnSpecialObject 中 - 到 SpecialClass。它总是与属性相同的类。

That's why I would like to do something like this:

这就是为什么我想做这样的事情:

class MYBaseClass
{
   protected List<Object> MyInternalObjects;
}

class MyClass
{
   public SpecialClass MyVeryOwnSpecialObject
   {
      get
      {
           return (GetPropertyType()) MyInteralObjects[System.Reflection.MethodBase.GetCurrentMethod().Name];
      }
   }
}

And now concerns: Ok, what for? Because further in my application I will have all benefits of safe types and so on (intellisense).

现在担心:好的,有什么用?因为在我的应用程序中,我将拥有安全类型等(智能感知)的所有好处。

Second one: but now you will lost type safety in this place? No. Because I'm very sure that I have object of my type on a list.

第二个:但是现在你会在这个地方失去类型安全吗?不。因为我非常确定我的列表中有我的类型的对象。

采纳答案by Tomasz Smykowski

Now it seems to be impossible, but soon will be available with new feature in .NET 4.0 called "dynamic":

现在这似乎是不可能的,但很快就会在 .NET 4.0 中提供名为“动态”的新功能:

http://www.codeguru.com/vb/vbnet30/article.php/c15645__4/

http://www.codeguru.com/vb/vbnet30/article.php/c15645__4/

回答by weiqure

Object o = (TargetType) ex;

This code is useless. You might have a type on the right but it's still only an object on the left side. You can't use functionality specific to TargetType like this.

这段代码没用。您可能在右侧有一个类型,但它仍然只是左侧的一个对象。您不能像这样使用特定于 TargetType 的功能。



This is how you can invoke a method of an unknown object of a given type:

这是调用给定类型的未知对象的方法的方法:

object myObject = new UnknownType();
Type t = typeof(UnknownType); // myObject.GetType() would also work
MethodInfo sayHelloMethod = t.GetMethod("SayHello");
sayHelloMethod.Invoke(myObject, null);

With this UnknownType class:

使用这个 UnknownType 类:

class UnknownType
{
    public void SayHello()
    {
        Console.WriteLine("Hello world.");
    }
}

回答by Lazarus

if (ex is ExampleClass) 
{
  ExampleClass myObject = (ExampleClass)ex;
}

That would do it but I guess the question is what are you trying to achieve and why? I often find that if something seems really, reallydifficult then I'm probably doing it wrong.

那会做到,但我想问题是你想要达到什么目标,为什么?我经常发现,如果某件事看起来真的非常困难,那么我可能做错了。

回答by Jon Skeet

Usually a desire to do this indicates a misunderstanding. However, there arevery occasionally legitimate reasons to do this. It depends on whether or not it's going to be a reference conversionvs an unboxing or user-defined conversion.

通常,这样做的愿望表明存在误解。然而,很偶然的正当理由这样做。这取决于它是参考转换还是拆箱或用户定义的转换。

If it's a reference conversion, that means the actual value (the reference) will remain entirely unchanged. All the cast does is perform a check and then copy the value. That has no real use - you can perform the check using Type.IsAssignableFrominstead, and just use the implicit cast to objectif you want it in a variable of type object.

如果是引用转换,则意味着实际值(引用)将完全保持不变。强制转换所做的只是执行检查,然后复制值。这没有实际用途 - 您可以使用Type.IsAssignableFrom代替执行检查,object如果您希望在 type 变量中使用隐式转换,则只需使用隐式转换object

The main point of casting is to provide the compilerwith more information. Now if you only know the type at executiontime, that clearly can't help the compiler.

强制转换的主要目的是为编译器提供更多信息。现在,如果您只在执行时知道类型,那显然无法帮助编译器。

What do you plan to do with oafter you've performed the cast? If you can explain that, we can try to explain how to achieve the effect you're after.

演完o演员后你打算做什么?如果你能解释,我们可以试着解释如何达到你所追求的效果。

If you really want a user-defined conversion or an unboxing conversion to occur, that could be a different matter - but I suspectthat's not the case.

如果您真的希望发生用户定义的转换或拆箱转换,那可能是另一回事 - 但我怀疑情况并非如此。

EDIT: Having seen your update, your property is just declared to return CustomClass, so all you need is:

编辑:看到您的更新后,您的财产刚刚声明为 return CustomClass,因此您只需要:

public CustomClass MyClassOuter
{
   get
   {
        return (CustomClass) otherClass;
   }
}

I suspect you still haven't really given us all the information we need. Is that definitelyhow your property will be defined, with CustomClassbeing a definite type? Why were you trying to perform the cast dynamically when you know the property type?

我怀疑你还没有真正向我们提供我们需要的所有信息。这绝对是您的财产将被定义的方式,并且CustomClass是确定的类型吗?当您知道属性类型时,为什么要尝试动态执行转换?

EDIT: It sounds like you're just trying to save some typing - to make it easier to cut and paste. Don't. You know the type at compile-time, because you know the type of the property at compile-time (it's specified in the code just a few lines above). Use that type directly. Likewise don't try to get the name of the current method to work out the key to use. Just put the name in directly. Again, you know it at compile-time, so why be dynamic? I'm all for laziness when it makes sense, but in this case it just doesn't.

编辑:听起来您只是想节省一些输入 - 以便更轻松地剪切和粘贴。别。您在编译时知道类型,因为您在编译时知道属性的类型(它在上面几行代码中指定)。直接使用该类型。同样,不要尝试获取当前方法的名称来计算要使用的密钥。直接输入名字就行了。同样,您在编译时就知道它,那么为什么要动态呢?当有道理时,我完全赞成懒惰,但在这种情况下,事实并非如此。

回答by gzak

I'm not entirely sure what you're trying to do, but the impression I'm getting is that you'd like to have a single instance of some object which can "act like" many different types of objects, and you want to have getters which will allow you to view this one object in those various different ways very easily. In that case, I would suggest making a single getter method (not a property), like so:

我不完全确定您要做什么,但我得到的印象是您希望拥有某个对象的单个实例,该实例可以“表现得像”许多不同类型的对象,并且您想要有 getter 可以让你很容易地以各种不同的方式查看这个对象。在这种情况下,我建议创建一个 getter 方法(不是属性),如下所示:

public T Get<T>()
{
   return (T)myObject;
}

Then you would call it like so:

然后你会这样称呼它:

Foo foo = box.Get<Foo>();
Bar bar = box.Get<Bar>();
// etc...

Two things to note: this is definitely not type-safe, since you can pass any type for T, including types for which the cast will fail. You can constrain it a little, like so:

需要注意的两件事:这绝对不是类型安全的,因为您可以为 T 传递任何类型,包括转换将失败的类型。你可以限制它一点,像这样:

public T Get<T>() where T : SomeBaseType

Which will cause a compile error if you try to use a type which is incompatible with SomeBaseType, but I'm not sure that's totally robust. But hopefully this gets you most of the way there.

如果您尝试使用与 不兼容的类型,这将导致编译错误SomeBaseType,但我不确定这是否完全可靠。但希望这能让你完成大部分工作。

Is this what you had in mind?

这是你想到的吗?