【问题标题】:Use an interface for dynamic vars使用动态变量的接口
【发布时间】:2014-01-16 03:35:02
【问题描述】:

在 C# 中,是否可以为动态 var 使用手写界面?我正在使用 COM 自动化与应用程序交互,尽管我可以访问如下属性:

dynamic shape = comObject;
int Width = (int)shape.Width;

..我真的更喜欢用这个:

interface PageShape {
   int Width {get; set;}
   int Height {get; set;}
}
PageShape shape2 = (PageShape)comObject;

int Width = shape.Width; // COOL!

这可能吗?这通常会触发InvalidCastException,但我只是想知道它是否可能。关于我的具体场景的更多细节here

【问题讨论】:

标签: c# dynamic interface com


【解决方案1】:

由于您无法访问原始代码,因此您必须将其添加到您自己的层中。据我所知,您将无法绕过从 dynamic 到实际接口的转换,但您可以在一层中进行此转换,然后使用实际的 OOP。

这可能是一个示例实现:

void Main()
{
    IPageShape pageInfo = ComTransformer.GetPageShape(comObject);
}

interface IPageShape {
   int Width { get; set; }
   int Height { get; set; }
}

class PageShapeImpl : IPageShape {
    public int Width { get; set; }
    public int Height { get; set; }
}

static class ComTransformer {
    public static IPageShape GetPageShape(dynamic obj) {
        return new PageShapeImpl {
            Width = (int) obj.Width,
            Height = (int) obj.Height
        };
    }
}

【讨论】:

  • @Geotarget:是的,差不多。您将对象的转换包装在一个实用程序类中,以使转换在整个项目中易于访问,并将执行此操作的逻辑组合在一起。 quick search 强化了我的感觉,即如果不自己明确地转换对象,就不可能做到这一点。 -- 编辑:没关系,显式转换器不起作用。
【解决方案2】:

dynamic 不会使实际对象动态化,除非它是动态对象,它只是告诉编译器在运行时解析变量。

所以如果动态变量中的对象是一个实现了接口的对象,它就会工作,否则你会得到一个强制转换异常

例如,这将在第一次调用时起作用,但在第二次调用时不起作用:

interface ITheInterface{}
class TheClass : ITheInterface{}
class OtherClass {}
public static void Main(string[] args)
{ 
    NextMethod(new TheClass());
    NextMethod(new OTherClass());

}

public static NextMethod(dynamic d)
{
    //works on the first call but not the second
    TheInterface ti = (ITheInterface)d;

} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 2018-11-07
    • 1970-01-01
    • 2014-04-24
    相关资源
    最近更新 更多