How to find control property default properties at runtime in C #

I have a control ... any System.Windows.Forms.Control . let's say for example. label.

I want to find the default value for its property called Enabled (maybe any property, for that matter). How to do it?

1) See in this case we have a label. The default value for the Enabled label is true.

2) Now, at runtime, suppose I want to know what is the default value for the Enabled property ... how do I know?

3) To begin with, I have an object of my control. From this object I can get the current value for the "Enabled" property, but not the DEFAULT value.

One possible approach to this issue could be:

1) Determine the type of control at run time. 2) Initialize it using your default constructor. 3) Find the value of the object of interest to us (this will, apparently, be the default value), and there ... we have the default value.

But in this case ... I do not know my control before hand. All I know is that it can be any control from System.Windows.Forms.Control . So how do I even initialize it and get its object? Is it possible?

Do you have an alternative solution / better approach?

+5
source share
4 answers

! , , (public, no parameters):

public static object GetDefaultPropertyValue(Type type, string propertyName)
{
        if (type.GetConstructor(new Type[] { }) == null)
            throw new Exception(type + " doesn't have a default constructor, so there is no default instance to get a default property value from.");
        var obj = Activator.CreateInstance(type);
        return type.GetProperty(propertyName).GetValue(obj, new object[] { });
}

, , , , .

+4

( ) .

public class DefaultValueChecker<T> where T : System.Windows.Forms.Control, new()
{
    public bool DetermineDefaultValue() {
        var control = new T();
        return control.Enabled;
    }
}
+3

. :

  • ()

. , .

As for the second part of the question, this can be solved using reflection: take a look at the class Type(runtime type type) and the Activatorclass (instance type runtime type).

0
source

You can try using reflection and checking the DefaultValue attribute:

Type labelType = typeof(Label);
DefaultValueAttribute attr = (DefaultValueAttribute)labelType
    .GetProperty("AutoEllipsis")
    .GetCustomAttributes(typeof(Defaul tValueAttribute),true)
    .FirstOrDefault();
Console.WriteLine(attr.Value);

However, not all properties are annotated with this attribute, so not all default values ​​can be obtained this way.

0
source

All Articles