.NET Framework - Set all bool attributes at once
Asked By Joe Kovac
01-Jun-07 06:19 AM
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
BindingFlags
(1)
PropertyInfo
(1)
TypeDescriptor
(1)
BitVector32
(1)
SetValue
(1)
Compiler
(1)
Jon Skeet [C# MVP] replied...
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
Joe Kovac replied...
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.
Marc Gravell replied...
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
Aneesh P replied...
You can get your class using GetType method:
Type myType = Type.GetType("MyClass");
PropertyInfo pInfo = mytype.GetProperty("Property1") would give you
type infor abt Property1.
if(pInfo.PropertyType.Name == "bool")
pInfo.SetValue(myType, false,null);
This could help I hope. Please do some R&D, since I've not compiled
this code.
Aneesh P replied...
Ok. Marc's method is the apt one for use I think. I was taking a long
route it seems.
Marc Gravell replied...
It isn't really any more/less verbose - especially if you had used
GetProperties()... the only real difference is the distinction between
reflection and the component-model. I tend to try and work with the
latter where possible, largely because it is what binding uses, and it
works with virtual properties so can be more flexible. But your code
would have worked too.
Marc
Joe Kovac replied...
Thanks to all, you brought me to the right context.
Though, I have one more problem:
Type t = typeof(StaticClass.SubClass);
// Static properties.
PropertyInfo[] pi = t.GetProperties(BindingFlags.Static |
BindingFlags.NonPublic | BindingFlags.Public);
foreach (PropertyInfo p in pi)
{
----> p.SetValue(StaticClass.SubClass, true, null);
}
My propeties are in a subclass of a static class. So I get following error:
Compiler Error Message: CS0119: 'StaticClass.SubClass' is a 'type',
which is not valid in the given context
I can "see" my properties. But I can`t set them.
Thanks for your help
Joe
Jon Skeet [C# MVP] replied...
Pass "null" as the first argument - you do not need to specify an
instance when the property is static.
Jon
Joe Kovac replied...
THANKS so much! It works all perfectly now!
Joe
Ignacio Machin \( .NET/ C# MVP \) replied...
Hi,
The first parameter of SetValue is the instance whose property you want to
change, as they are static there are no instance involved, just pass null.
new Test(); Type type = oTest.GetType(); / / Diese Zeile funktioniert wie gew?nscht type.InvokeMember("TestInt", BindingFlags.SetProperty | BindingFlags.SetField | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase, null, oTest, new obj[] { 1 }); / / Diese Zeile ergibt eine MissingMethodException type.InvokeMember("TestShort", BindingFlags.SetProperty | BindingFlags.SetField | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase, null, oTest, new obj[] { 1 }); / / Diese Zeile ergibt eine MissingMethodException
Exception End Try Next Catch ex As Exception End Try End Sub VB.NET Discussions BindingFlags.NonPublic (1) TreeViewName.Nodes (1) BindingFlags.Instance (1) BindingFlags.Public (1) BindingFlags (1) PropertyInfo (1) TabControl (1) GetXMLText (1) If you want to read and write the Text value its value. Dim t As Type = Me.GetType() Dim fiList As FieldInfo() = t.GetFields _ (BindingFlags.Instance Or BindingFlags.NonPublic) For Each fi As FieldInfo In fiList Dim ftype As Type = fi.FieldType Dim ftextprop As PropertyInfo = _ ftype.GetProperty("Text", _ BindingFlags.Instance Or BindingFlags.Public) If (ftextprop IsNot Nothing) Then
Why is my GetFields(BindingFlags.Instance | BindingFlags.Public) not working? (Sample working code included) .NET Framework My code in see the NonPublic members, but not the Public ones. Full sample code below. FieldInfo[] publicFieldInfos = t.GetFields(BindingFlags.Instance | BindingFlags.Public); is returning nothing. Note, I am trying to get at the properties on the I am going bonkers on this one. . . . the msdn example works with the 2 flags (BindingFlags.Instance | BindingFlags.Public). . . . .but my mini inheritance example below is not. THANKS in advance. private void RunTest1() { try { textBox1.Text = string.Empty; Type t = typeof(MyInheritedClass); / / Look at the BindingFlags * ** NonPublic * ** int fieldCount = 0; while (null ! = t) { fieldCount + = t.GetFields BindingFlags.Instance | BindingFlags.NonPublic).Length; FieldInfo[] nonPublicFieldInfos = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); foreach (FieldInfo field
current class (not inherited) and public thanks C# Discussions SOSIsTemplateAttribute (1) GetCustomAttributes (1) SOSIsTemplate (1) BindingFlags (1) PropertyInfo (1) GetHashCode (1) On Wed, 25 Feb 2009 11:01:01 -0800, raulavi Do you their attributes? What are you having trouble with? You can pass an appropriate combination of BindingFlags to the Type.GetProperties() method to specify which properties you really want. Pete trouble with trouble getting the correct properties? If the latter, then my previous suggestion about using the BindingFlags should solve your problem. If the former, then you should be able to just get all the attributes with the GetCustomAttributes() method for PropertyInfo. If that doesn't answer your question, then you should try to do a better 2 class). simple using bindingflag to get what you want like this typeof(myclass).GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); Best regards. nguyen.panther RIGHT ON THE TARGET, thanks so much. nguyen.panther or
approaches I need to resolve? C# Discussions Microsoft.SqlServer.Management.UI.ConnectionDlg (1) System.Reflection.BindingFlags.InvokeMethod (1) AppDomain.CurrentDomain.BaseDirectory (1) Registry.LocalMachine.OpenSubKey (1) SQL Server 2005 (1) Personalization GetField("ServerType").GetValue(null); int count; string[] engines; count = (int)typePersonalization.InvokeMember ("GetCountByServerType", System.Reflection.BindingFlags.InvokeMethod, null, null, new object[] { guidServerType }); engines = new string[count]; typePersonalization.InvokeMember("GetStringsByServerType", System.Reflection.BindingFlags.InvokeMethod, null, null, new object[] { guidServerType, engines, count }); non reflection version: (works ok returns 12 Rivers wrote, On 10-11-2009 0:42: In my experience it helps to pass BindingFLags.Instance | BindingFlags.Public as well for instance based methods. And BindingFlags.Static | BindingFlags.Public for static methods. Whay I do not understand is why you are using reflection reflection to invoke methods etc. (as far as I know anyway) I tried that also: BindingFlags bindFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod; count = (int)typePersonalization.InvokeMember("GetCountByServerType", bindFlags, null, null