开发者

COM object in base class - access via field or property?

开发者 https://www.devze.com 2022-12-17 19:12 出处:网络
I\'ve inherited a codebase of C# dlls that are called via COM-interop (or so it has been described).The C# code also uses COM objects internally to perform the basic functionality of the parent applic

I've inherited a codebase of C# dlls that are called via COM-interop (or so it has been described). The C# code also uses COM objects internally to perform the basic functionality of the parent application.

I'm refactoring some of the DRY violations out of the code because finding duplications in 100,000 lines of code across 50 or 60 dlls is inefficient. I've come across a use of COM objects in abstract base classes that I'd like to standardize a bit, but I haven't found a clearly definitive statement anywhere about this particular use of COM objects in C#.

Our code currently has several base classes that contain COM objects, coded like this:

public abstract class SomeBaseClass()
{
   protected IComObject comObject;

   protected virtual void Initialize(IComObject comObject)
   {
      this.comObject = comObject;
   }

   protected SomeBaseClass() { }
}

To prevent this.comObject from being set in other than Initialize(), I'd like to implement these base classes like this:

public abstract class SomeBaseClass()
{
   private IComObject comObject;

   protected IComObject ComObject
   {
      get { return comObject; }
   }

   protected virtual void Initialize(IComObject comObject)
   {
      this.comObject = comObject;
   }

   protected SomeBaseClass() { }
}

In my opinion the second example looks better and gives me more control over the internal comObject.

Currently, the existing derived cla开发者_StackOverflow中文版sses (C#) do not set the base class comObject directly, instead using Initialize(), but there is nothing to prevent them from assigning to the base class comObject directly. I want to prevent the potential future mistake of assigning to comObject outside of Initialize().

Is there some reason that the second base class implementation of COM object handling will not work? In my limited testing it seems to work fine, but you guys are smarter than I am.

thanks!


There is nothing involving COM Interop that would make the second case any different than the first. Feel free to adjust the access modifier of the field to private.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号