如何在C#中获取对象的子对象?

时间:2016-04-22 07:26:40

标签: c# .net object

在VB.net中,这段代码没问题:

Dim oPS as Object= CreateObject("Photoshop.Application.10")
Dim oDocument as Object= oPS.ActiveDocument

但在C#中,此代码出现错误:

Object oPS = COMCreateObject("Photoshop.Application.10");
Object oDocument = oPS.ActiveDocument;

构建时出错

Error   2   'object' does not contain a definition for 'ActiveDocument' and no extension method 'ActiveDocument' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

如何在C#中获取对象的子对象(相同的vb.net)?

3 个答案:

答案 0 :(得分:4)

使用dynamic关键字代替object

dynamic oPS = COMCreateObject("Photoshop.Application.10");
dynamic oDocument = oPS.ActiveDocument;

MSDN参考此处:https://msdn.microsoft.com/en-us/library/dd264736.aspx

答案 1 :(得分:1)

在.net 4或更高版本中,您应该使用dynamic来实现此目的。这应该是:

var _type= Type.GetTypeFromProgID("Photoshop.Application.10");
dynamic inst= Activator.CreateInstance(_type);
inst.Visible = true;

答案 2 :(得分:1)

为您的问题使用动态关键字。