小编sol*_*ish的帖子

如何在项目targets.net 4.0中使用async关键字

我想在.net 4.0中创建的项目中使用async关键字.

如果我去nuget.org网站,我寻找"异步",我有很多结果,但主要是我得到这个:

Visual Studio异步CTP(版本3,非官方)0.3.0

AsyncAwaitCTP 1.0.0

两者之间的差异是什么?

asynchronous .net-4.0 async-await c#-5.0

25
推荐指数
1
解决办法
1万
查看次数

如何在REST WCF服务中接受任意JSON对象?

我想实现这样的服务方法:

[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 c# rest wcf json

8
推荐指数
1
解决办法
3204
查看次数

我可以让 Json.net 使用“主”构造函数反序列化 C# 9 记录类型,就好像它有 [JsonConstructor] 一样?

在 .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#。 …

c# json json.net c#-9.0

7
推荐指数
2
解决办法
2710
查看次数

标签 统计

c# ×2

json ×2

.net ×1

.net-4.0 ×1

async-await ×1

asynchronous ×1

c#-5.0 ×1

c#-9.0 ×1

json.net ×1

rest ×1

wcf ×1