确定Object的类型并转换为类型

时间:2013-12-06 20:41:37

标签: c# object casting

我希望能够确定一个对象的类型,然后将该对象转换为它应该是什么。我会尽力解释。下面的代码不起作用,但它显示了我想要实现的目标。我需要返回未知对象类型的大小;可以是按钮,面板,表格等。

public static void Draw(object AnimateObject)
{
    try
        {
            // Set the starting coordinants for our graphics drawing
            int y = 0;
            int x = 0;
            // Set the end coordinants for our graphics drawing
            int width = AnimateObject.Size.Width;
            int height = AnimateObject.Size.Height;

            // More graphics related stuff here...
        }
}

通常情况下,我可以将对象转换为应该使用的对象并完成它,但是一旦“未知对象”部分出现,我就有点死路了。我确信我可以超载一百万次并让它找到合适的类型,但我希望有一种更明智的方法来做到这一点。

2 个答案:

答案 0 :(得分:2)

让所有这些类型的百万个实现一个具有Size属性的接口,然后键入该接口的参数,而不是不断地对类型进行编译时检查以尝试支持任何可能有一个大小。

如果某些对象无法修改以实现该接口,请考虑添加一个额外的委托作为参数,通过执行以下操作来选择大小:

public static void Draw<T>(T AnimateObject, Func<T, Size> sizeSelector)

然后,您可以在方法内部使用该委托来访问对象的大小。

然后调用者可以这样写:

Draw(square, obj => obj.Size);

答案 1 :(得分:1)

由于AnimateObject的类型未知,您可以依赖于动态运行时:

public static void Draw(dynamic AnimateObject)
{
    try
    {
        // Set the starting coordinants for our graphics drawing
        int y = 0;
        int x = 0;
        // Set the end coordinants for our graphics drawing
        int width = AnimateObject.Size.Width;
        int height = AnimateObject.Size.Height;

        // More graphics related stuff here...
    }
    catch  { /* type doesn't respond as expected */ }
}
相关问题