gpt4 book ai didi

c# - 是否可以从 C# 中的对象修改或删除匿名类型?

转载 作者:太空宇宙 更新时间:2023-11-03 19:18:25 24 4
gpt4 key购买 nike

我有一段代码如下:

var selected = “A”;
bool isSelected = selected == "A" || selected == "C";
var codeLists = new
{
displayProperty1 = isSelected ? "property1" : null,
displayProperty2 = isSelected ? "property2" : null,
displayProperty3 = selected == "C" ? "property3" : null
};

因此,我的目标是消除不满足条件的属性。在上面的代码中,selected"A"。因此,displayProperty3 的值为 null。但我想消除 displayProperty3,这样如果选择的是“A”,那么对象中应该只有 2 个属性

如果有任何适当且有效的方法可以做到这一点,我将不胜感激。

最佳答案

不,匿名类型仍然遵循其他类型的规则,只是它们没有在编译时显式定义。要执行您想要的操作,您必须定义两种不同的类型。

如果您不想在您的 UI 中显示该属性(例如,如果您希望绑定(bind)到自动生成的网格并且您不希望它成为一列),那么处理在你的用户界面中。

但是,如果您必须这样做,则必须创建两种不同的类型(匿名或显式):

var selected = "A";
bool isSelected = selected == "A" || selected == "C";
dynamic codeLists;
if(selected == "C")
{
codeLists = new
{
displayProperty1 = isSelected ? "property1" : null,
displayProperty2 = isSelected ? "property2" : null
};
}
else
{
codeLists = new
{
displayProperty1 = isSelected ? "property1" : null,
displayProperty2 = isSelected ? "property2" : null,
displayProperty3 = "property3"
};
}

如果您创建一个具有公共(public)属性的基类型会更好,但无论哪种方式它们都将是两种不同的类型:

public class CodeList
{
public string displayProperty1 {get; set;}
public string displayProperty2 {get; set;}
}

public class CodeListC : CodeList
{
public string displayProperty3 {get; set;}
// Other two properties will be inherited
}

关于c# - 是否可以从 C# 中的对象修改或删除匿名类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14365858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com