为事件分配函数时为什么使用'+ ='?

时间:2015-12-31 06:41:22

标签: c# events

在C#中,事件语法为

public static byte[] Serialize(this ITableEntity entity)
{
MemoryStream ms = new MemoryStream();
using(var messageWriter = new ODataMessageWriter(new Message(ms), new ODataMessageWriterSettings()))
{
    // Create an entry writer to write a top-level entry to the message.
    ODataWriter entryWriter = messageWriter.CreateODataEntryWriter();
    var writeODataEntity =typeof(TableConstants).Assembly.GetType("Microsoft.WindowsAzure.Storage.Table.Protocol.TableOperationHttpWebRequestFactory")
        .GetMethod("WriteOdataEntity", BindingFlags.NonPublic | BindingFlags.Static);

    writeODataEntity.Invoke(null, new object[] { entity, TableOperationType.Insert, null, entryWriter });
    return ms.ToArray();
}            
}

public static void Deserialize(this ITableEntity entity, byte[] value)
{
MemoryStream ms = new MemoryStream(value);
using(ODataMessageReader messageReader = new ODataMessageReader(new Message(ms), new ODataMessageReaderSettings()))
{
    ODataReader reader = messageReader.CreateODataEntryReader();
    var readAndUpdateTableEntity = typeof(TableConstants).Assembly.GetType("Microsoft.WindowsAzure.Storage.Table.Protocol.TableOperationHttpResponseParsers")
        .GetMethod("ReadAndUpdateTableEntity", BindingFlags.NonPublic | BindingFlags.Static);
    reader.Read();
    readAndUpdateTableEntity.Invoke(null, new object[] { entity,  reader.Item, 31, null });
}
}

internal class Message : IODataResponseMessage
{
private readonly Stream stream;
private readonly Dictionary<string, string> headers = new Dictionary<string, string>();

public Message(Stream stream)
{
    this.stream = stream;
    SetHeader("Content-Type", "application/atom+xml");
}

public string GetHeader(string headerName)
{
    string value;
    headers.TryGetValue(headerName, out value);
    return value;
}

public void SetHeader(string headerName, string headerValue)
{
    this.headers.Add(headerName, headerValue);
}

public Stream GetStream()
{
    return this.stream;
}

public IEnumerable<KeyValuePair<string, string>> Headers
{
    get
    {
        return this.headers;
    }
}

public int StatusCode
{
    get;
    set;
}
}

为什么在设计C#语言时使用event += onEvent 运算符而不是像

这样的设计选择更好?
+=

(或类似的东西)?为什么它首先被这样使用?

1 个答案:

答案 0 :(得分:4)

正如Steve在评论中所说,“+ =”只是一种语法糖 - 编程语言中的语法,旨在使事情更容易阅读或表达