I have code similar to this:
class Foo {
Dictionary<Type, Object> _dict;
void Create(string myType, string myValue)
{
var instance = Type.Instanciate(myType) // How do I do this?
if (var.IsPrimitive)
{
var.GetType().Parse(myValue) // I know this is there...how to invoke?
Dictionary[instance.GetType()] = instance;
}
}
T GetValue<T>(T myType) { return (T)_dict[T]; }
}
// Populate with values
foo.Create("System.Int32", "15");
foo.Create("System.String", "My String");
foo.Create("System.Boolean", "False");
// Access a value
bool b = GetValue(b);
So my questions are:
a) How do I instantiate the type
b) Parse the type value from a string when Parse is supported.
Type.GetType()
Activator.CreateInstance
(You don't actually need this in your code.) Convert.ChangeType
Note that if the type isn't in mscorlib
or the currently executing assembly, you'll need to include the assembly name (and version information if it's strongly named).
Here's a complete example using your original code. Note that GetValue
doesn't need a normal parameter, as you've already given the type parameter (T).
using System;
using System.Collections.Generic;
public class Foo {
Dictionary<Type, Object> _dict = new Dictionary<Type, Object>();
public void Create(string myType, string myValue)
{
Type type = Type.GetType(myType);
object value = Convert.ChangeType(myValue, type);
_dict[type] = value;
}
public T GetValue<T>() { return (T)_dict[typeof(T)]; }
}
class Test
{
static void Main()
{
Foo foo = new Foo();
// Populate with values
foo.Create("System.Int32", "15");
foo.Create("System.String", "My String");
foo.Create("System.Boolean", "False");
Console.WriteLine(foo.GetValue<int>());
Console.WriteLine(foo.GetValue<string>());
Console.WriteLine(foo.GetValue<bool>());
}
}
a) How do I instantiate the type
You're looking for System.Activator.CreateInstance .
b) Parse the type value from a string when Parse is supported.
You're looking for System.Convert.ChangeType .
using System.Reflection;
public void Create(string myType, string myValue)
{
Type type = Type.GetType(myType);
if (type.IsPrimitive)
{
MethodInfo Parse = type.GetMethod("Parse");
Parse.Invoke(null, new object[] { myValue });
...
}
}
You can try Activator.CreateInstance
It has signatures receiving a type and without parameters, or with an array of ojects that while be the parameters
One more thing: keeping a reference to your new instance in the Dictionary could have an unintended consequence: The Dictionary's reference to the object will keep it from ever being collected. If that what you intend, then that's okay, but just be very sure you thing through all the implications of that first.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.