共用方式為


CA1408: Do not use AutoDual ClassInterfaceType

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
RuleId CA1408
Category Microsoft.Interoperability
Breaking change Breaking

Cause

A Component Object Model (COM) visible type is marked with the ClassInterfaceAttribute attribute set to the AutoDual value of ClassInterfaceType.

Rule description

Types that use a dual interface enable clients to bind to a specific interface layout. Any changes in a future version to the layout of the type or any base types will break COM clients that bind to the interface. By default, if the ClassInterfaceAttribute attribute is not specified, a dispatch-only interface is used.

Unless marked otherwise, all public nongeneric types are visible to COM; all nonpublic and generic types are invisible to COM.

How to fix violations

To fix a violation of this rule, change the value of the ClassInterfaceAttribute attribute to the None value of ClassInterfaceType and explicitly define the interface.

When to suppress warnings

Do not suppress a warning from this rule unless it is certain that the layout of the type and its base types will not change in a future version.

Example

The following example shows a class that violates the rule and a re-declaration of the class to use an explicit interface.

using System;
using System.Runtime.InteropServices;

[assembly: ComVisible(true)]
namespace InteroperabilityLibrary
{
   // This violates the rule.
   [ClassInterface(ClassInterfaceType.AutoDual)]
   public class DualInterface
   {
      public void SomeMethod() {}
   }

   public interface IExplicitInterface
   {
      void SomeMethod();
   }

   [ClassInterface(ClassInterfaceType.None)]
   public class ExplicitInterface : IExplicitInterface
   {
      public void SomeMethod() {}
   }
}
Imports System
Imports System.Runtime.InteropServices

<Assembly: ComVisibleAttribute(True)>
Namespace InteroperabilityLibrary

   ' This violates the rule.
   <ClassInterfaceAttribute(ClassInterfaceType.AutoDual)> _ 
   Public Class DualInterface
      Public Sub SomeSub
      End Sub
   End Class

   Public Interface IExplicitInterface
      Sub SomeSub
   End Interface

   <ClassInterfaceAttribute(ClassInterfaceType.None)> _ 
   Public Class ExplicitInterface
      Implements IExplicitInterface

      Public Sub SomeSub Implements IExplicitInterface.SomeSub
      End Sub

   End Class

End Namespace

CA1403: Auto layout types should not be COM visible

CA1412: Mark ComSource Interfaces as IDispatch

See also