C # PropertyInfo (shared)

Let's say I have this class:

class Test123<T> where T : struct
{
    public Nullable<T> Test {get;set;}
}

and this class

class Test321
{
   public Test123<int> Test {get;set;}
}

So, to the problem we can say that I want to create Test321 through reflection and set "Test" with a value, how to get a generic type?

+3
source share
3 answers

Since you start with Test321, the easiest way to get this type is with a property:

Type type = typeof(Test321);
object obj1 = Activator.CreateInstance(type);
PropertyInfo prop1 = type.GetProperty("Test");
object obj2 = Activator.CreateInstance(prop1.PropertyType);
PropertyInfo prop2 = prop1.PropertyType.GetProperty("Test");
prop2.SetValue(obj2, 123, null);
prop1.SetValue(obj1, obj2, null);

Or do you want to find T?

Type t = prop1.PropertyType.GetGenericArguments()[0];
+13
source

That should make it more or less. I do not have access to Visual Studio right now, but this may give you some idea on how to instantiate a type type and set its property.

// Define the generic type.
var generic = typeof(Test123<>);

// Specify the type used by the generic type.
var specific = generic.MakeGenericType(new Type[] { typeof(int)});

// Create the final type (Test123<int>)
var instance = Activator.CreateInstance(specific, true);

And to set the value:

// Get the property info of the property to set.
PropertyInfo property = instance.GetType().GetProperty("Test");

// Set the value on the instance.
property.SetValue(instance, 1 /* The value to set */, null)
0
source

Try something like this:

using System;
using System.Reflection;

namespace test {

    class Test123<T> 
        where T : struct {
        public Nullable<T> Test { get; set; }
    }

    class Test321 {
        public Test123<int> Test { get; set; }
    }

    class Program {

        public static void Main() {

            Type test123Type = typeof(Test123<>);
            Type test123Type_int = test123Type.MakeGenericType(typeof(int));
            object test123_int = Activator.CreateInstance(test123Type_int);

            object test321 = Activator.CreateInstance(typeof(Test321));
            PropertyInfo test_prop = test321.GetType().GetProperty("Test");
            test_prop.GetSetMethod().Invoke(test321, new object[] { test123_int });

        }

    }
}

Check the Overview of reflections and generalizations in msdn.

0
source

Source: https://habr.com/ru/post/1715869/


All Articles