Microsoft内部属性-此属性没有setter

本文关键字:属性 setter 内部 Microsoft | 更新日期: 2023-09-27 18:03:12

我正在用ILSpy仔细阅读一些系统类时,从System.Internal.HandleCollector类中发现了这一点:

internal sealed class HandleCollector
{        
    ... bunch of stuff removed ...
    internal static event HandleChangeEventHandler HandleAdded
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        add
        {
            HandleCollector.HandleAdded = (HandleChangeEventHandler)Delegate.Combine(HandleCollector.HandleAdded, value);
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        remove
        {
            HandleCollector.HandleAdded = (HandleChangeEventHandler)Delegate.Remove(HandleCollector.HandleAdded, value);
        }
    }
    ... bunch of stuff removed ...
}

当VisualStudio抱怨(我复制了类(该属性没有setter时,Microsoft如何编译它?有人能解释为什么我的VS副本抱怨(构建标志?(?

此属性没有setter

错误出现在每个HandleCollector.HandleAdded =语句上。

Microsoft内部属性-此属性没有setter

我们不需要猜测MS源代码是什么,因为它在这里可用。

这是HandleCollector.cs:中HandleAdded的声明

internal static event HandleChangeEventHandler HandleAdded; 

它是一个自动实现的事件。问题出在ILSpy的反编译上。也许你应该提交一个bug。

如果您希望它在add和remove实现中使用赋值进行编译,则需要使用字段。

像这样:

internal sealed class HandleCollector
{
    private static HandleChangeEventHandler HandleAddedField;
    internal static event HandleChangeEventHandler HandleAdded
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        add
        {
            HandleCollector.HandleAddedField = (HandleChangeEventHandler)Delegate.Combine(HandleCollector.HandleAddedField, value);
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        remove
        {
            HandleCollector.HandleAddedField = (HandleChangeEventHandler)Delegate.Remove(HandleCollector.HandleAddedField, value);
        }
    }
}