How do I do "like a class" where "Class" is a string name?

I have a set of classes on my system. So, I have a simple config file with a collection of class names.

And I want to run the code like this:

(object as Class).name="some text"; 

      

Where Class is its class name string from the config file. Maybe I should use reflection for this?

Thank!

+3


source to share


3 answers


You can ignore the type and use directly dynamic

(which internally uses reflection) ...

object obj = ...
dynamic dyn = obj;
dyn.name = "some text";

      

This only works if name

- public

. Otherwise, you can use reflection ...

If name

is a property:



Type type = obj.GetType();
PropertyInfo prop = type.GetProperty("name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
prop.SetValue(obj, "some text");

      

If this field:

Type type = obj.GetType();
FieldInfo field = type.GetField("name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
field.SetValue(obj, "some text");

      

+6


source


If the class name is not available at compile time, you must use reflection or DLR (dynamic) to set the property.



More details in the answer here Set property of an object using reflection

+1


source


It's hard to say what your use case is, but here's another angle to your question that might help. I am assuming that all the classes you can specify in your config have the same property (i.e. name

). If so, you can use all classes to implement the same interface, then you don't need to worry about the class name. For example:

Your interface:

public interface IName
{
    string Name { get; set; }
}

      

The class that uses the interface:

public class Something : IName
{
    public string Name { get; set; }
    public string AnotherProperty { get; set; }
}

      

And the method that any object that implements the interface uses IName

:

public void DoSomething(IName input)
{
    Console.WriteLine(input.Name);
}

      

So now you can call the method without worrying about class names:

var someObject = new Something();
someObject.Name = "Bob";

DoSomething(someObject);

      

+1


source







All Articles