Reputation: 357
I want to do something like: User input name of class + fields. Code finds if a Class with that name has ever been declared. Code creates Class with fields.
I know I can do this with many switch cases, but can I somewhat automate this based on the user input? The name that the user inputs will be the Class name. I'm doing this in C#.
Upvotes: 1
Views: 552
Reputation: 23675
The System.Reflection.Emit
namespace can provide you the tools you need in order to create dynamic classes at runtime. However, if you never used it previously, the task you are trying to accomplish can become quite hard. Of course, premade code could help a lot, and I think that here you can find plenty.
But I propose you an alternative path. Maybe not as flexible, but certainly interesting. It involves the use of DynamicObject class:
public class DynamicClass : DynamicObject
{
private Dictionary<String, KeyValuePair<Type, Object>> m_Fields;
public DynamicClass(List<Field> fields)
{
m_Fields = new Dictionary<String, KeyValuePair<Type, Object>>();
fields.ForEach(x => m_Fields.Add
(
x.FieldName,
new KeyValuePair<Type, Object>(x.FieldType, null)
));
}
public override Boolean TryGetMember(GetMemberBinder binder, out Object result)
{
if (m_Fields.ContainsKey(binder.Name))
{
result = m_Fields[binder.Name].Value;
return true;
}
result = null;
return false;
}
public override Boolean TrySetMember(SetMemberBinder binder, Object value)
{
if (m_Fields.ContainsKey(binder.Name))
{
Type type = m_Fields[binder.Name].Key;
if (value.GetType() == type)
{
m_Fields[binder.Name] = new KeyValuePair<Type, Object>(type, value);
return true;
}
}
return false;
}
}
Usage example (remember that Field
is a small and simple class with two properties, Type FieldType
and String FieldName
that you have to implement by yourself):
List<Field>() fields = new List<Field>()
{
new Field("ID", typeof(Int32)),
new Field("Name", typeof(String))
};
dynamic myObj = new DynamicClass(fields);
myObj.ID = 10;
myObj.Name= "A";
Console.WriteLine(myObj.ID.ToString() + ") " + myObj.Name);
Upvotes: 1