将动态类型的实例传递给泛型类中的泛型方法 [英] Passing an instance of a dynamic type to a generic method in a generic class

查看:74
本文介绍了将动态类型的实例传递给泛型类中的泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个公开泛型方法的泛型类.此方法接收泛型对象的实例作为参数并修改此实例.

I have a generic class that exposes a generic method. This method receives an instance of the generic object as parameter and modifies this instance.

示例类:

public class GenericClass<T>
{
    public T GenericMethod(T obj)
    {
        // modify the object in some (arbitrary) way
        IEnumerable<FieldInfo> fields = obj.GetType().GetRuntimeFields();
        foreach (FieldInfo field in fields)
        {
            if (field.FieldType == typeof(string))
            {
                field.SetValue(obj, "This field's string value was modified");
            }
        }

        return obj;
    }
}

如果我有一个类型(abc):

If I have a type (abc):

public class abc
{
    public string a;
    public string b;
    public int c;
}

我可以这样调用这个方法:

I can call this method as follows:

GenericClass<abc> myGeneric = new GenericClass<abc>();
var myObject = myGeneric.GenericMethod(new abc());

//Confirm success by printing one of the fields
Console.Writeline(((abc)myObject).a);

现在,我的实际问题是:

我将如何使用仅在运行时已知的类型(而不是上面的类型 abc)来调用相同的泛型方法.我还想在将它传递给 GenericMethod 时将其实例化,就像我在上面为 abc 所做的那样.

How would I call this same Generic method, using a type that is only known at run-time (as opposed to type abc above). I also want to instantiate this this as I pass it in to the GenericMethod, just like I did for abc above.

例如(我知道这是完全错误的)

Type MyType;

GenericClass<MyType> myGeneric = new GenericClass<MyType>();
var myObject = myGeneric.GenericMethod(new MyType());

由于未知类型的成功无法通过打印可能不存在的字段a"来确认,我可以打印所有字符串字段的值,但这超出了问题的范围.

推荐答案

回答您的问题:

var type = typeof(abc);
object instanceToModify = new abc();

var typeToCreate = typeof(GenericClass<>).MakeGenericType(type);
var methodToCall = typeToCreate.GetMethod("GenericMethod");

var genericClassInstance = Activator.CreateInstance(typeToCreate);
methodToCall.Invoke(genericClassInstance, new[] { instanceToModify });

演示

但是:

如果您的类型仅在运行时已知,您的实例必须在声明为 objectdynamic 的变量中处理.在这种情况下,您可以将方法签名更改为:

If your type is only known at runtime your instance must be handled in a variable declared as object or dynamic. In that case you can change your method signature to:

public object GenericMethod(object obj)
{
    // modify the object in some (arbitrary) way
    IEnumerable<FieldInfo> fields = obj.GetType().GetRuntimeFields();
    foreach (var field in fields)
    {
        if (field.FieldType == typeof(string))
        {
            field.SetValue(obj, "This field's string value was modified");
        }
    }

    return obj;
}

不需要通用的类/方法.

There's no need for a generic class/method.

这篇关于将动态类型的实例传递给泛型类中的泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆