如果您使用VBA,則使用COM Interop。一般來說它被認爲是很好的做法,明確定義了COM接口,即代替:
[ComVisible]
public class MyClass
{
...
}
你應該使用:
[ComVisible]
public interface IMyClass
{
...
}
[ComVisible]
[ClassInterface(ClassInterfaceType.None)]
public class MyClass : IMyClass
{
...
}
一旦你做到這一點,很簡單:你只需要避免可空類型在IMyClass
接口,並明確實現它,如:
[ComVisible]
public interface IMyClass
{
...
public int MyInt {get; }
}
[ComVisible]
[ClassInterface(ClassInterfaceType.None)]
public class MyClass : IMyClass
{
...
public int? MyInt {get; }
int IMyClass.MyInt
{
get { return this.MyInt ?? 0; }
}
}
順便以這種方式使用顯式接口實現的另一個好處是,您可以在傳播到COM Interop客戶端之前記錄異常,並獲取當異常傳播到COM時丟失的有用堆棧跟蹤信息。例如。
[ComVisible]
public interface IMyClass
{
...
public void MyMethod();
}
[ComVisible]
[ClassInterface(ClassInterfaceType.None)]
public class MyClass : IMyClass
{
...
public void MyMethod()
{
}
void IMyClass.MyMethod()
{
try
{
this.MyMethod();
}
catch(Exception ex)
{
... log exception ex here ...
throw;
}
}
}
來源
2012-09-27 07:43:22
Joe
謝謝,你沒錯,T4對20個班級來說太多了:) –