C#: instantiating classes from XML

前端 未结 8 771
情歌与酒
情歌与酒 2021-02-04 09:05

What I have is a collection of classes that all implement the same interface but can be pretty wildly different under the hood. I want to have a config file control which of the

8条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 09:37

    Reflection or XML-serialization is what you're looking for.

    Using reflection you could look up the type using something like this

    public IYourInterface GetClass(string className)
    {
        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) 
        {            
            foreach (Type type in asm.GetTypes())
            {
                if (type.Name == className)
                    return Activator.CreateInstance(type) as IYourInterface;
            }   
        }
    
        return null;
    }
    

    Note that this will go through all assemblies. You might want to reduce it to only include the currently executing assembly.

    For assigning property values you also use reflection. Something along the lines of

    IYourInterface o = GetClass("class1");
    o.GetType().GetProperty("prop1").SetValue(o, "foo", null);
    

    While reflection might be the most flexible solution you should also take a look at XML-serialization in order to skip doing the heavy lifting yourself.

提交回复
热议问题