是否可以从c#中的对象修改或删除匿名类型? [英] Is it possible to modify or remove an anonymous type from an object in c#?

查看:61
本文介绍了是否可以从c#中的对象修改或删除匿名类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段类似下面的代码:

I have a piece of code like below:

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
};

因此,我的目标是消除不满足条件的财产.在上面的代码中,所选"A" .因此, displayProperty3 的值为 null .但是我想消除 displayProperty3 ,以便如果选择的是"A",则对象中应该只有 2个属性.

So, my goal is to eliminate a property if it does not satisfy a condition. In the above code, selected is "A". So, displayProperty3 would have a value of null. But I want to eliminate displayProperty3 so that if selected is "A", then there should be only 2 properties in the object.

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

If there is any proper and efficient way to do this, I would be grateful for it.

推荐答案

否,匿名类型仍然遵循其他类型的规则,只是在编译时未明确定义它们.要执行您想要的操作,您必须定义两种不同的类型.

No, an anonymous type still follows the rules of other types, they're just not explicitly defined at compile-time. To do what you want you'd have to define two different types.

如果您不想在用户界面中显示该属性(例如,如果您绑定到自动生成的网格,并且您不希望将其作为列),则处理在您的用户界面中.

If you don't want to show that property in your UI (e.g. if you ware binding to a grid that's auto-generated and you don't want that to be a column) then deal with that in your UI.

但是,如果必须执行此操作,则必须创建两种不同的类型(匿名或显式):

However, if you HAVE to do this, you'd have to create two different types (either anonymous or explicit):

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" 
    }; 
}

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

It would be better if you created a base type with the common properties, but either way they are going to be two different types:

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#中的对象修改或删除匿名类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆