更新:2007 年 11 月
| TypeName | AvoidStaticMembersInComVisibleTypes | 
| CheckId | CA1407 | 
| 类别 | Microsoft.Interoperability | 
| 是否重大更改 | 否 | 
原因
明确标记为对 COM 可见的类型包含 publicstatic 方法。
规则说明
COM 不支持 static 方法。
此规则忽略属性 (Property) 和事件访问器、运算符重载方法、使用 System.Runtime.InteropServices.ComRegisterFunctionAttribute 属性 (Attribute) 或 System.Runtime.InteropServices.ComUnregisterFunctionAttribute 属性 (Attribute) 标记的方法。
默认情况下,以下内容对 COM 是可见的:程序集、公共类型、公共类型中的公共实例成员和公共值类型的所有成员。
要引发此规则,必须将一个程序集级别的 ComRegisterFunctionAttribute 设置为 false,并且将类 ComRegisterFunctionAttribute 设置为 true,如以下代码所示。
using System;
using System.Runtime.InteropServices; 
[assembly: ComVisible(false)] 
namespace Samples
{    
    [ComVisible(true)]
    public class MyClass
    {
        public static void DoSomething()
        {
        }
    }
}
如何解决冲突
若要解决与此规则的冲突,请将设计更改为使用提供与 static 方法相同的功能的实例方法。
何时禁止显示警告
如果 COM 客户端不需要访问 static 方法提供的功能,则可以安全地禁止显示与此规则有关的警告。
冲突的示例
说明
下面的示例演示一个与此规则冲突的 static 方法。
代码
using System;
using System.Runtime.InteropServices;
using System.Collections.ObjectModel; 
[assembly: ComVisible(false)] 
namespace Samples
{    
    [ComVisible(true)]    
    public class Book    
    {        
        private Collection<string> _Pages = new Collection<string>();         
        public Book()        
        {        
        }         
        public Collection<string> Pages        
        {            
            get { return _Pages; }        
        }                
        // Violates this rule        
        public static Book FromPages(string[] pages)        
        {            
            if (pages == null)                
                throw new ArgumentNullException("pages");             
            Book book = new Book();             
            foreach (string page in pages)            
            {                
                book.Pages.Add(page);            
            }             return book;        
        }    
    }
}
注释
在此示例中,不能从 COM 中调用 Book.FromPages 方法。
解决冲突的示例
说明
若要解决上一示例中的冲突,可将该方法更改为实例方法,但在此实例中这样做不起作用。更好的解决方案是将 ComVisible(false) 显式应用于方法,以使该方法对其他开发人员而言清楚明了,并且从 COM 中不可见。
下面的示例将 ComRegisterFunctionAttribute 应用于该方法。
代码
using System;
using System.Runtime.InteropServices;
using System.Collections.ObjectModel;
[assembly: ComVisible(false)]
namespace Samples
{
    [ComVisible(true)]
    public class Book
    {
        private Collection<string> _Pages = new Collection<string>();
        public Book()
        {
        }
        public Collection<string> Pages
        {
            get { return _Pages; }
        }
        [ComVisible(false)]
        public static Book FromPages(string[] pages)
        {
            if (pages == null)
                throw new ArgumentNullException("pages");
            Book book = new Book();
            foreach (string page in pages)
            {
                book.Pages.Add(page);
            }
            return book;
        }
    }
}
相关规则
避免对 Visual Basic 6 客户端使用 Int64 参数