我想在.net 4.0中创建的项目中使用async关键字.
如果我去nuget.org网站,我寻找"异步",我有很多结果,但主要是我得到这个:
Visual Studio异步CTP(版本3,非官方)0.3.0
两者之间的差异是什么?
我想实现这样的服务方法:
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
public void MakeShape(string shape, string color, IDictionary<string, object> moreArgs)
{
if (shape == "circle")
{
MakeCircle(color, moreArgs);
}
}
Run Code Online (Sandbox Code Playgroud)
我的客户POST对象如下:
{
"shape":"circle",
"color": "blue",
"radius": 42,
"filled":true,
"annotation": {"date":"1/1/2012", "owner":"George"}
}
Run Code Online (Sandbox Code Playgroud)
在调用MakeCircle时,moreArgs将有3个条目("radius","filled"和一个名为"annotation"的字典,其中包含2个键值对.)
我到目前为止最好的是:
//Step 1: get the raw JSON by accepting a Stream with BodyStyle=WebMessageBodyStyle.Bare
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Bare)]
public void MakeShape(Stream jsonStream)
{
//Step 2: parse it into a Dictionary with JavaScriptSerializer or JSON.net
StreamReader reader = new StreamReader(jsonStream); …Run Code Online (Sandbox Code Playgroud) 在 .NET 5.0 上使用 C# 9,我有一堆记录类型,如下所示:
public record SomethingHappenedEvent(Guid Id, object TheThing, string WhatHappened)
{
public SomethingHappenedEvent(object theThing, string whatHappened)
: this(Guid.NewGuid(), theThing, whatHappened)
{ }
}
Run Code Online (Sandbox Code Playgroud)
正如您所料,它们被序列化并发送到其他地方进行处理。发送者调用双参数构造函数并获得一个新的 Id,但反序列化器需要使用记录声明隐含的“主要”3 参数构造函数。我正在使用 Newtonsoft Json.NET,我当然希望这能奏效:
var record = new SomethingHappenedEvent("roof", "caught fire");
var json = JsonConvert.SerializeObject(record);
var otherSideRecord = JsonConvert.DeserializeObject<SomethingHappenedEvent>(json);
Assert.AreEqual(record, otherSideRecord);
Run Code Online (Sandbox Code Playgroud)
当然不是。它抛出 JsonSerializationException。它找不到正确的构造函数,因为有两个,既不是默认的零参数构造函数,也没有标记 JsonConstructorAttribute。我的问题实际上是“我有什么选择来获得类似的东西?”。这会很棒:
[JsonConstructor]
public record SomethingHappenedEvent(Guid Id, object TheThing, string WhatHappened)
{
public SomethingHappenedEvent(object theThing, string whatHappened)
: this(Guid.NewGuid(), theThing, whatHappened)
{ }
}
Run Code Online (Sandbox Code Playgroud)
但这会尝试将该属性应用于无效的类型。这是 C# 中的语法错误,但显然它适用于 F#。 …