铸造对象回到原始类型 [英] Cast Boxed Object back to Original Type

查看:124
本文介绍了铸造对象回到原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有两个答案之一,不可能或非常简单,我忽略了明显的Google查询。

I expect there's one of two answers to this, either impossible or extremely simple and I've overlooked the obvious Google query.

根本的问题是我有通过 EventHandler 传入一个通用对象,该对象将对象进行模糊处理,并使真实类型模糊;只有在运行时我知道对象是什么。

The underlying issue is that I have a generic object being passed in via an EventHandler that boxes the object and obfuscates the true type; only at runtime do I know what the object is.

诚然,动态关键字可以解决问题,但是我想不会失去智能感知和一切,如果我可以避免它。另外,它不解决不知道通用对象的每个属性没有大量的反射。

Admittedly the dynamic keyword can get around the issue, but I'd like to not lose IntelliSense and everything if I can avoid it. Plus, it doesn't solve not knowing what each of the properties of the generic object are without massive amounts of reflection.

编辑:这个想法是能够确定在方法参数中的对象的真实类型,然后将该对象转换为真实类型,而不事先知道该对象。这只是一个简化的例子。盒装可能是错误的术语。

The idea is to be able to determine the true type of the an object in a method parameter, and then cast that object as it's true type without knowing it in advance. This is but a simplified example. Boxed may have been the wrong term.

一个例子:

public class Program
{
    static void Main(string[] args)
    {
        var container = new Container<Containee>(
            new Containee
            {
                Property1 = Guid.NewGuid(),
                Property2 = "I'm a property!",
                Property3 = DateTime.Now
            }
        );

        var boxed = (object)container;

        var originalType = boxed.GetType();

        // DOES NOT COMPILE: would like an operation like this
        // EDIT: Request for more detail
        var actualType = boxed as originalType;
        actualType.Entity.Property2 = "But I like this better.";
    }
}

public class Containee
{
    public Guid Property1 { get; set; } 
    public string Property2 { get; set; }
    public DateTime Property3 { get; set; }
}

public class Container<T>
{
    public Container(T entity)
    {
        Entity = entity;
    }

    public T Entity { get; internal set; }
}

显然不会编译,因为没有一种方式可以投射作为变量。但是,我希望有一种方法来获取对实际对象和类型的引用,或至少是一种动态重新创建类型的方法。

Clearly that won't compile, as there's not really a way to cast as a variable. However, I'm hoping there's a way to get a reference to the actual object and type, or at least, a way to dynamically re-create the type.

I期待有一些简单的我俯瞰,或一个更好的方法来摆脱它一般。关键是能够将任何对象包装在容器中,并在后面找出它是什么。

I expect there's something simple I'm overlooking, or a better way to get around it in general. The point is to be able to wrap any object in the container, and figure out later what it was.

推荐答案


想法是能够在方法参数中确定一个对象的真实类型

The idea is to be able to determine the true type of the an object in a method parameter

这很简单(你已经在这样做了)。

That's easy enough (and you're already doing it).

Type actualType = param.GetType();

这将使您获得对象的实际具体类型

That will get you the actual concrete type of the object


然后转换该对象,因为它是真实的类型

and then cast that object as it's true type

这是事情脱落铁轨有点。 C#中的铸造操作员(用户称之为铸造)可以做两件事:

This is where things come off the rails a bit. The casting operator in C# (usage of which is what people refer to as "casting") can do two things:


  1. 使用类型特定通过将转换应用于现有对象来创建新对象的显式转换(请注意,这是创建的新的引用;原始对象的类型永远不会更改)

  2. 允许开发人员将对象引用为其继承层次结构中与当前提供的类型不同的类型(或在层次结构中低于当前引用的类型实现的接口) li>
  1. Use type-specific explicit conversions to create a new object by applying the conversion to the existing object (note that this is a new reference that is created; the original object's type is never changed)
  2. Allow the developer to reference an object as a type that is at a different level in its inheritance hierarchy than is currently provided (or an interface that is implemented on a type that is lower in the hierarchy than is currently referenced)

在你的情况下,第一个选项是正确的;像所有运算符一样,转换运算符不是多态的。也就是说,只有在正在引用的类型中定义了运算符,而不是被引用的对象。如果你想进一步澄清这一点,让我知道,但我不认为这是你的问题的一个关键,所以我不会进一步去,除非问。

In your case, the first option is right out; the casting operator, like all operators, is not polymorphic. That is, an operator is only applied if it is defined on the type that is being referenced, not the object that's being referenced. If you'd like further clarification on this, let me know, but I don't think it's germane to your question so I'm not going to go into it further unless asked.

第二个选项是可以实际应用于您的唯一选项,但请考虑您想要执行此操作的唯一两个原因:

The second option is the only option that could realistically apply to you, but consider the only two reasons you would want to do this:


  1. 所以你可以将对象引用为一个比当前提供的具体类型更低的特定类型(在你的情况下,你的对象是一个对象所以这几乎是一样高)

  2. 所以你可以将对象引用到层次结构中的更高的类型,这样你可以绕过隐藏(但不能覆盖)成员。

  1. So that you can refer to the object as a specific concrete type that is at a lower level than is currently provided (in your case, your object is an object, so that's pretty much as high as it goes)
  2. So that you can refer to an object as a type that is higher in the hierarchy so that you can bypass hidden (but not overridden) members.

(绝大多数演员都是理由#1)

(The vast majority of casts are for reason #1)

您希望使用这些选项的原因是,您可以使用强类型对象并使用该类型定义的各种成员。但是,所有这些都只适用于您在编写代码时知道的类型。在编译时将其转换为未知的类型是没有意义的,因为转换不会对实际对象执行任何操作(它仍然是它的真实类型;唯一改变的类型是

The reason you would want to use either of those options is so that you can have a strongly-typed object and use the various members defined on that type. But all of these things only apply to types that you know when you're writing the code. It doesn't make sense to cast to a type that is unknown at compile time, as casting doesn't do anything to the actual object (it is, and shall remain, its true type; the only thing that changes is the type of the variable by which you reference the object).

如果您可以进一步说明您实际想要的内容,做(完整的代码,你想要或期望它的工作),我可能能够提供一些建模更接近你想要的东西,但正如它所描述的那样具体,我可以得到。

If you can provide a further fleshed-out example of what you're actually trying to do (complete with code as you'd either like or expect it to work), I might be able to provide something modeled a little closer to what you want, but as it's described this is as specific as I can get.

这篇关于铸造对象回到原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆