一次设置所有bool属性 [英] Set all bool attributes at once

查看:87
本文介绍了一次设置所有bool属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!


我有一个包含许多bool属性的类。

现在我想将它们全部设置为true或false,而不会忘记

一个或者另一个。

这么简单吗? (例如使用反射)


谢谢


Joe

解决方案

< blockquote> 6月1日上午11点19分,Joe Kovac< Joe ... @nospam.comwrote:


我有一个包含许多bool属性的类。

现在我想将它们全部设置为true或false,而不会忘记

中的一个。

任何简单的方法都可以? (例如使用反射)



反射基本上是*唯一的*方法。现在,它的哪一部分你觉得很难找?你要设置这些*属性*,还是仅仅字段?
?你以前用过反射吗?


Jon


Jon Skeet [C#MVP]写道:


6月1日上午11点19分,Joe Kovac< Joe ... @ nospam.comwrote:


>我有一个有很多bool属性的类。
现在我想把它们全部设置为true或false,而不会忘记
一个或另一个。
任何简单的方法去做? (例如使用反射)



反射基本上是*唯一的*方法。现在,它的哪一部分你觉得很难找?你要设置这些*属性*,还是仅仅字段?
?你以前用过反射吗?


Jon



我从未使用反射直到现在。有关元素是属性

而不仅仅是字段。

目前我发现这两个部分都很棘手。查找属性并进行设置。


如下所示。如果这是你自己的类,请注意

存储大量bool的效率低于在内部使用位掩码

(例如BitVector32或[Flags]枚举,或只是一个

int)。


object obj = null; // TODO

bool value = false;

foreach(PropertyDescriptor prop in

TypeDescriptor.GetProperties(obj)){

if(!prop.IsReadOnly&& prop.PropertyType ==

typeof(bool)){

prop.SetValue(obj,value); < br $>
}

}


Marc


Hi!

I have a class with many bool attributes.
Now I want to set them all at once to true or false, without forgetting
one or the other.
Any easy way to do that? (e.g. using reflection)

Thanks

Joe

解决方案

On Jun 1, 11:19 am, Joe Kovac <Joe...@nospam.comwrote:

I have a class with many bool attributes.
Now I want to set them all at once to true or false, without forgetting
one or the other.
Any easy way to do that? (e.g. using reflection)

Reflection is basically the *only* way to do it. Now, which part of it
are you finding tricky? Are these *properties* you want to set, or
just fields? Have you used reflection before at all?

Jon


Jon Skeet [C# MVP] wrote:

On Jun 1, 11:19 am, Joe Kovac <Joe...@nospam.comwrote:

>I have a class with many bool attributes.
Now I want to set them all at once to true or false, without forgetting
one or the other.
Any easy way to do that? (e.g. using reflection)


Reflection is basically the *only* way to do it. Now, which part of it
are you finding tricky? Are these *properties* you want to set, or
just fields? Have you used reflection before at all?

Jon

I never used reflection until now. The concerned elements are properties
and not just fields.
Currently I find both parts tricky. Finding the properties and setting them.


Something like below, then. If this is your own class, note that
storing lots of bools is less efficient than using a bit-mask
internally (e.g. a BitVector32, or a [Flags] enumeration, or just an
int).

object obj = null; // TODO
bool value = false;
foreach (PropertyDescriptor prop in
TypeDescriptor.GetProperties(obj)) {
if (!prop.IsReadOnly && prop.PropertyType ==
typeof(bool)) {
prop.SetValue(obj, value);
}
}

Marc


这篇关于一次设置所有bool属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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