【问题标题】:Determine type of Object and cast as type确定对象的类型并转换为类型
【发布时间】:2013-12-06 20:41:37
【问题描述】:

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

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...
        }
}

通常我可以将对象投射到应有的状态并完成它,但是一旦出现“未知对象”部分,我就陷入了死胡同。我确信我可以将这个东西重载一百万次并让它找到正确的类型,但我希望有一种更明智的方法来做到这一点。

【问题讨论】:

  • 看来你需要dynamic 而不是object
  • 所有这些类型是否有一个共同的父级具有Size?这就是多态性的全部意义所在。
  • 你可以试试dynamic。它将所有检查从编译时移到运行时。或者找到所有其他派生自(或接口然后实现)的通用类型并创建泛型方法。
  • @Candide 动态修复了它!如果发布,我将接受作为答案。

标签: c# object casting


【解决方案1】:

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

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

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

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

然后调用者可以这样写:

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

【讨论】:

    【解决方案2】:

    由于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 */ }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 2012-05-14
      • 1970-01-01
      • 2018-11-27
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多