简体   繁体   中英

Send type from string variable to generic method

I have a generic method and I want to send to it a type taken from a string variable.

The signature of my generic method is:

public ICollection<TEntity> agregarItems<TEntity>(ComboBox cb) where TEntity : new()

And I want to do this:

Type tipo = Type.GetType("MyNamespace." + cb.Name);

cliente.GetType().GetProperty(cb.Name).SetValue(cliente,
        agregarItems<tipo>(cb), null);

Where cb is a ComboBox object and cliente is an instance of a class.

cb.Name could be "Phone" and the Phone class already exists in MyNamespace.

Because tipo isn't defined formally I get the following error:

The type or namespace name 'tipo' could not be found (are you missing a using directive or an assembly reference?)

I need a workaround that let me send a not formally defined type to the generic method.

Type tipo = Type.GetType("TypeName");

only works for very basic types.

The types you want to reference might be in an assembly like System.Web, System, etc. It is not sufficient that this assembly is referenced, you also need to tell the runtime in which assembly your type is.

So try

Type tipo = Type.GetType(YourType.AssemblyQualifiedName);

instead of

Type tipo = Type.GetType(YourType.FullName);

Additionally, you are using a runtime determined type (tipo) to create a compile-time determined generic overload. That cannot work - ever.

You need to modify the generic method to pass the type as argument.

What you have to do is to create the instance with the type you obtained in the way presented here (with an Activator ):

How to dynamically create generic C# object using reflection?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM