非只读的替代匿名类型 [英] Non-read only alternative to anonymous types

查看:146
本文介绍了非只读的替代匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,一个匿名类型可以如下:

In C#, an anonymous type can be as follows:

method doStuff(){
     var myVar = new {
         a = false, 
         b = true
     }

     if (myVar.a) 
     {
         // Do stuff             
     }
}

但是,以下不会编译:

However, the following will not compile:

method doStuff(){
     var myVar = new {
         a = false, 
         b = true
     }

     if (myVar.a) 
     {
         myVar.b = true;
     }
}

这是因为myVar的的字段是只读的,不能被分配​​到。似乎想要做这样的事,后者是相当普遍的;也许是我见过的最好的解决方法就是定义的方法之外的结构。

This is because myVar's fields are read-only and cannot be assigned to. It seems wanting to do something like the latter is fairly common; perhaps the best solution I've seen is to just define a struct outside the method.

不过,真的没有别的办法,使上述块工作的?它困扰我的理由是,myVar的是这一领域的局部变量,所以它看起来像它应该只使用它的方法内引用。此外,需要以放置结构的方法的外面可以使一个对象的声明从它的使用很远,特别是在一个长的方法

However, is there really no other way to make the above block work? The reason it bothers me is, myVar is a local variable of this field, so it seems like it should only be referred to inside the method that uses it. Besides, needing to place the struct outside of the method can make the declaration of an object quite far from its use, especially in a long method.

,有没有匿名类型,这将让我定义一个结构这样的(我意识到结构存在于C#和必须在外面定义的方法),而不使其成为只读的方法吗?如果没有,是有什么根本性的错误想这样做,我应该使用不同的方法?

Put in another way, is there an alternative to anonymous types which will allow me to define a "struct" like this (I realize struct exists in C# and must be defined outside of a method) without making it read-only? If no, is there something fundamentally wrong with wanting to do this, and should I be using a different approach?

推荐答案

没有,你必须创建自己的类或结构如果你希望它是可变做到这一点(preferrably一类 - 可变结构太可怕)。

No, you'll have to create your own class or struct to do this (preferrably a class if you want it to be mutable - mutable structs are horrible).

如果你不关心等于 / 的ToString / GetHash $ C $ ç实现,这是pretty容易:

If you don't care about Equals/ToString/GetHashCode implementations, that's pretty easy:

public class MyClass {
    public bool Foo { get; set; }
    public bool Bar { get; set; }
}

(我还是使用属性,而不是领域,各种原因。)

我个人通常会发现自己想要的的一成不变的类型,我可以等方法之间传递 - 我想现有的匿名类型功能的命名版本...

Personally I usually find myself wanting an immutable type which I can pass between methods etc - I want a named version of the existing anonymous type feature...

这篇关于非只读的替代匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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