相关疑难解决方法(0)

将实例化的System.Type作为泛型类的类型参数传递

标题有点模糊.我想知道的是,如果可能的话:

string typeName = <read type name from somwhere>;
Type myType = Type.GetType(typeName);

MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>();
Run Code Online (Sandbox Code Playgroud)

显然,MyGenericClass被描述为:

public class MyGenericClass<T>
Run Code Online (Sandbox Code Playgroud)

现在,编译器抱怨'找不到类型或命名空间'myType'."必须有办法做到这一点.

.net c# generics

174
推荐指数
2
解决办法
8万
查看次数

C#:在给定对Type的引用的情况下实例化List

假设在C#中myType是对某些人的引用Type.myType仅使用,是否可以创建一个List对象myType

例如,在下面的代码中,虽然它是错误的,但我想实例化via

new List <myType> ( ) .

using System ;
using System.Reflection ;
using System.Collections.Generic ;

class MyClass
    {
    }

class MainClass
    {

    public static void Main ( string [] args )
        {

        Type  myType  =  typeof ( MyClass ) ;

        List < myType >  myList  =  new List < myType > ( ) ;

        }

    }
Run Code Online (Sandbox Code Playgroud)

c# list

4
推荐指数
1
解决办法
3088
查看次数

字符串值变量

这是场景

string dataTypeName = "Employee";
Run Code Online (Sandbox Code Playgroud)

Employee是哪个类,我想创建它的对象.

Type EmployeeObject = Type.GetType(dataTypeName);
Run Code Online (Sandbox Code Playgroud)

现在我想像这样实例化Employee的对象

EmployeeObject emp1 = new Employee();
Run Code Online (Sandbox Code Playgroud)

可能吗.但是这种方法不起作用.我对反思没有强烈的想法.请指导我.

c# reflection

1
推荐指数
1
解决办法
87
查看次数

使用动态生成的类型创建泛型类的对象

我有一个通用的类

public  class MyClass<T>
{
   public List<T> Translate(List<T> list, params string[] names)
           {
            //do something here,modify list and return list
       }
    }
Run Code Online (Sandbox Code Playgroud)

现在我可以轻松创建它的实例

MyClass<Employee> obj= new MyClass<Employee>(); OR
MyClass<Vehicle> obj = new MyClass<Vehicle>();
Run Code Online (Sandbox Code Playgroud)

我可以称我的方法为

    obj.Translate(Mylist of employee or vehicle type,"param1","param2")
Run Code Online (Sandbox Code Playgroud)

但在我的情况下,我不知道在运行时生成的类型T,请参阅下面的代码

String classname = string.Empty;

if(Classtype == 1)
{
    classname = "Employee"
}
else if(classtype == 2)
{
    classname = "Vehicle"
}
Run Code Online (Sandbox Code Playgroud)

我想要下面的东西......所以我可以创建这个泛型类的实例

MyClass<typeof(classname)> empp = new MyClass<typeof(classname)>();

    empp.Translate(MyList,"param1","param2")
Run Code Online (Sandbox Code Playgroud)

请建议,我该怎么做.

c# generics reflection properties class

1
推荐指数
1
解决办法
6290
查看次数

标签 统计

c# ×4

generics ×2

reflection ×2

.net ×1

class ×1

list ×1

properties ×1