【问题标题】:Determining how an object is cast inside a method with Reflection使用反射确定对象如何在方法内转换
【发布时间】:2014-01-02 17:36:54
【问题描述】:

如何使用反射来确定从方法内部转换对象的方式?

例子:

给定这种类型,它可以被隐式转换并分配为 int、float 或 string:

public class VersatileType {

    public int intVal = 10;
    public float floatVal = 1.5f;
    public string stringVal = "words";

    // implicit convertions

    // ints
    public static implicit operator int(VersatileType vt) {
        return vt.intVal;
    }

    public static implicit operator VersatileType(int val) {
        VersatileType vt = new VersatileType();
        vt.intVal = val;
        return vt;
    }

    // floats
    public static implicit operator float(VersatileType vt) {
        return vt.floatVal;
    }

    public static implicit operator VersatileType(float val) {
        VersatileType vt = new VersatileType();
        vt.floatVal = val;
        return vt;
    }

    // strings
    public static implicit operator string(VersatileType vt) {
        return vt.stringVal;
    }

    public static implicit operator VersatileType(string val) {
        VersatileType vt = new VersatileType();
        vt.stringVal = val;
        return vt;
    }
}

以及执行一些隐式转换和分配的给定方法:

public VersatileType obj;

public void CastAndAssignObj() {

    obj = 0;
    string text = obj;
}

有没有办法使用反射(或任何其他过程)来确定“obj”是如何从 CastAndassignObj() 内部转换/分配的?

对于上面的示例,我希望得到一个包含 intstring 类型的集合。

非常感谢-

【问题讨论】:

    标签: c# reflection casting implicit assign


    【解决方案1】:

    反射在这里对你没有好处,因为它总是会产生VersatileType,并且具有stringintfloat 类型的3 个属性,反射不会告诉你正在使用哪一个。我认为做你想做的最简单的方法是添加一个标志(isInt、isFloat、isString)或停止初始化这些值,这样你就可以说

       if (myVersatileType.StringVal != null)
           // guess we're a string
    

    您不能使用反射,因为它不会创建不同的类型。只有一种类型,它具有三个值,并且只使用其中一个。

    【讨论】:

    • 不幸的是,我需要在不运行代码的情况下做出此决定。听起来很疯狂,但我需要确定“obj”的使用方式,以便我可以在与最终运行上述代码的可执行文件不同的运行时环境中将信息用作 Unity 编辑器工具的一部分。我希望这有任何意义。
    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 2010-12-15
    相关资源
    最近更新 更多