2009-06-04 26 views
7

Sé que esto no funciona, pero ¿alguien tiene alguna manera de hacerlo funcionar?Mecanografía dinámica en C#

object obj = new object(); 
MyType typObj = new MyType(); 
obj = typObj; 
Type objType = typObj.GetType(); 
List<objType> list = new List<objType>(); 
list.add((objType) obj); 

EDIT:

Aquí está el código actual: http://github.com/vimae/Nisme/blob/4aa18943214a7fd4ec6585384d167b10f0f81029/Lala.API/XmlParser.cs

El método que estoy tratando de racionalizar es SingleNodeCollection

Como se puede ver, por lo que actualmente utiliza la reflexión hackeado métodos.

+2

Lo ¿Estás tratando de hacerlo? –

+0

¿Qué estás tratando de lograr? –

+2

@Daniel: Parece que está intentando crear una lista del tipo de un objeto ya existente. – Welbog

Respuesta

10

Parece que se está perdiendo una solución obvia:

object obj = new object(); 
MyType typObj = new MyType(); 
obj = typObj; 
List<MyType> list = new List<MyType>(); 
list.Add((MyType) obj); 

Si realmente necesita la ruta dinámica, entonces se podría hacer algo como esto:

object obj = new object(); 
MyType typObj = new MyType(); 
obj = typObj; 
Type objType = typObj.GetType(); 

Type listType = typeof(List<>); 
Type creatableList = listType.MakeGenericType(objType); 

object list = Activator.CreateInstance(creatableList); 
MethodInfo mi = creatableList.GetMethod("Add"); 
mi.Invoke(list, new object[] {obj}); 
+0

¿Esto solo está en .Net 3.5? – Skizz

+0

No, 2.0 y superior. –

+0

Buen código, solo resolvió un problema para mí. :) –

1

Es necesario reflexión:

constructor = typeof (MyType).GetConstructor() // doing this from memory, the typeof might be wrong, I'm sure someone will edit it 
typObj = (MyType) constructor.Invoke() 

También se puede hacer para genéricos, pero eso es un poco más complicado.

1

Puede hacer algo como esto usando Generics, aunque no estoy seguro de qué va a ser.

public List<T> TypedList<T>() where T : new() 
{ 
    object obj = new object(); 
    T typObj = new T(); 
    obj = typObj; 
    List<T> list = new List<T>(); 
    list.Add((T)obj); 
    return list; 
} 
0
object obj = new object(); 
Type objType = obj.GetType(); 
IList list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(objType)); 
list.Add(obj); 

Con esto se obtendrá un error de tiempo de ejecución si se intenta poner algo en la lista que no es asignable a partir tipoObj.

-2

no estoy del todo seguro de lo que está tratando de hacer, sino que este trabajo:

var obj = new MyType();

que podría estar mal entendido su pregunta, sin embargo.

(I editado esto para fijar código de ejemplo que no se compile, gracias por el comentario)

+0

var obj; es una declaración inválida var es una palabra clave implícita, lo que significa que el compilador determinará qué tipo es. Con la declaración var obj; el compilador no tendría suficiente información para determinar el tipo. –

0

más rápido sería utilizar Reflection.Emit Here's un ejemplo sencillo de utilizar para crear instancias de un Reflection.Emit concreta arbitraria escriba en tiempo de ejecución. Para sus propósitos, solo necesita que llame al ctor de List en lugar de a T.ctor como en el ejemplo.

0

aunque parezca respondió, todavía no lo entiendo :)

¿No sería útil tener la "typeToReturn" como argumento a la función genérica?

public List<T> SingleNodeCollection<T>(String xPath, XPathNavigator navigator) 
    where T : new() 
{ 
    XPathNodeIterator nodes = navigator.Select(xPath); 
    List<T> returnedList = new List<T>(nodes.Count); 
    ... 
    T newObj = new T(); 
    ... 
    Type t = typeof(T); // need the type anyway? 
} 
0
public class myClass 
    { 
    } 

    myClass instance = new myClass(); 

    Type t = instance.GetType; 

// arriba es sólo para mostrar la obtención de un tipo ...

public object GetListOfType(Type t) 
{ 
    Type listType = typeof(List<>); 
    var listOfType = listType.MakeGenericType(t); 

    var listOfMyClassInstance = Activator.CreateInstance(listOfType); 

    return listOfMyClassInstance; 
} 

pero con el tiempo que tiene que echar ... usando su tipo directamente

List<object> listOfMyClass = GetListOfType(t); 
    listOfMyClass.Add(myClassInstance); 

    ((myClass)listOfMyClass[0]).SomeProperty 
Cuestiones relacionadas