相关疑难解决方法(0)

使用包含Type的变量创建Generic <T>类型实例

是否可以实现以下代码?我知道它不起作用,但我想知道是否有解决方法?

Type k = typeof(double);
List<k> lst = new List<k>();
Run Code Online (Sandbox Code Playgroud)

c# generics types instance

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

通用方法使用运行时类型执行

我有以下代码:

 public class ClassExample
{

    void DoSomthing<T>(string name, T value)
    {
        SendToDatabase(name, value);
    }

    public class ParameterType
    {
        public readonly string Name;
        public readonly Type DisplayType;
        public readonly string Value;

        public ParameterType(string name, Type type, string value)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");
            if (type == null)
                throw new ArgumentNullException("type");

            this.Name = name;
            this.DisplayType = type;
            this.Value = value;
        }
    }

    public void GetTypes()
    {
        List<ParameterType> l = report.GetParameterTypes();

        foreach (ParameterType p in l)
        {
            DoSomthing<p.DisplayType>(p.Name, (p.DisplayType)p.Value);
        }

    }
} …
Run Code Online (Sandbox Code Playgroud)

c# generics methods

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

C#通用方法和动态类型问题

我有一个声明如下的泛型方法:

public void Duplicate<EntityType>() { ... }
Run Code Online (Sandbox Code Playgroud)

所以,一般来说使用它我只需要说:

myObject.Duplicate<int>()
Run Code Online (Sandbox Code Playgroud)

但是在这里,我想要做的是通过变量传递类型,但它不起作用,这是我尝试这样做的方式:

Type myType = anObject.GetType();
myObject.Duplicate<myType>();
Run Code Online (Sandbox Code Playgroud)

如果有人可以帮助我?

预先感谢.

c# generics parameters types

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

标签 统计

c# ×3

generics ×3

types ×2

instance ×1

methods ×1

parameters ×1