.NET7 包括对序列化器的许多改进System.Text.Json,其中之一是使用新[JsonPolymorphic]属性的类型的多态序列化。我正在尝试在我的 Asp.Net Web API 中使用它,但是尽管模型已正确设置,但它似乎并未序列化类型鉴别器。
仅当尝试通过网络发送对象时才会发生这种情况,当使用 JsonSerializer 时,一切似乎都运行良好。例如:
// This is my data model
[JsonPolymorphic]
[JsonDerivedType(typeof(SuccesfulResult), typeDiscriminator: "ok")]
[JsonDerivedType(typeof(ErrorResult), typeDiscriminator: "fail")]
public abstract record Result;
public record SuccesfulResult : Result;
public record ErrorResult(string Error) : Result;
Run Code Online (Sandbox Code Playgroud)
// Some test code that actually works
var testData = new Result[]
{
new SuccesfulResult(),
new ErrorResult("Whoops...")
};
var serialized = JsonSerializer.SerializeToDocument(testData);
// Serialized string looks like this:
// [{ "$type": "ok" }, { "$type": "fail", "error": "Whoops..." }] …Run Code Online (Sandbox Code Playgroud) 我正在开发一款有趣的小游戏,我偶然发现了一个与C#运营商混淆的时刻.这是代码:
public static InventorySlot FindSlotWithItem(this IInventory inventory, Type itemType)
{
return inventory.InventorySlots.FirstOrDefault(t => t is itemType);
}
Run Code Online (Sandbox Code Playgroud)
就目前而言,此代码无法编译,因为我的Visual Studio告诉我无法找到类型或命名空间名称'itemType'.我想知道为什么会这样,并在MSDN上寻找一些信息.这是我发现的:
是(C#参考):检查对象是否与给定类型兼容.例如,以下代码可以确定对象是MyObject类型的实例,还是从MyObject派生的类型
这些线让我更加困惑,因为我明确地将一个对象作为第一个参数传递,而类型作为第二个参数.我知道这与编译器查找名为"itemType"的类型这一事实有关,但这并不是我想要的行为.
请告诉我为什么这样的语法不起作用以及为什么'itemType'不被'is'运算符视为类型.
我有一段Elm代码(getProjectView函数为简洁而省略):
type Model = Maybe List Project
model : Model
model = Nothing
getView : Model -> Html any
getView model =
case model of
Just projects ->
ul [] (List.map getProjectView projects)
Nothing -> p [] [ text "Still loading..." ]
Run Code Online (Sandbox Code Playgroud)
当我尝试编译以下代码段时,编译器失败并出现以下错误:
-- TYPE MISMATCH --------- E:\dev\irrelephant-code\client\elm\Views\Projects.elm
Tag `Maybe.Just` is causing problems in this pattern match.
32| Just projects ->
^^^^^^^^^^^^^
The pattern matches things of type:
Maybe a
But the values it will actually be trying to match …Run Code Online (Sandbox Code Playgroud)