gpt4 book ai didi

c# - 如何使用反射通过引用传递参数

转载 作者:行者123 更新时间:2023-12-04 10:21:20 27 4
gpt4 key购买 nike

如何使用反射调用通过引用接受参数的方法(使用 ref 关键字)?JsonConverter<T>定义了以下方法:

public abstract T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options);
我持有一个派生类型但有泛型参数 T作为 Type对象而已。这不编译:
converter.GetType().GetMethod("Read").Invoke(ref reader, type, options);
澄清 Utf8JsonReader是一个结构。
我的问题不是关于获取要调用的方法,而是如何在不按值传递参数(并导致复制结构)的情况下执行此操作。

最佳答案

如果您有 T ,一切都会很简单:

// declare a delegate
private delegate T ReadDelegate(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options);

// create and invoke a delegate
var readDelegate = Delegate.CreateDelegate(typeof(ReadDelegate), converter, "Read") as ReadDelegate;
var result = readDelegate.Invoke(ref reader, type, options);

来源: second search result from Google

但既然你没有,事情就会变得更有趣。这是我的解决方案(不像我想要的那么干净,但它有效)。首先你需要一个补充类(class):
internal abstract class ReadHelper
{
public abstract object Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options);
}

internal class ReadHelper<T> : ReadHelper
{
private readonly ReadDelegate _readDelegate;

private delegate T ReadDelegate(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options);

public Reader(object converter)
{
_readDelegate = Delegate.CreateDelegate(typeof(ReadDelegate), converter, "Read") as ReadDelegate;
}

public override object Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
=> _readDelegate.Invoke(ref reader, type, options);
}

现在你可以这样使用它们:
// I assume you know how to get this:
// var converter = ...
// var typeOfT = ...
// var reader = ...
// var type = ...
// var options = ...

var readHelperType = typeof(ReadHelper<>).MakeGenericType(typeOfT);
var readHelper = Activator.CreateInstance(readerType, converter) as Reader;

// and finally:
var result = readHelper.Read(ref reader, type, options);

以防万一,您不知道如何获取 typeOfT :
private Type FindTypeOfT(object converter)
{
var type = converter.GetType();
while (type != null)
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(JsonConverter<>))
return type.GetGenericArguments()[0];
else
type = type.BaseType;

return null;
}

关于c# - 如何使用反射通过引用传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60830084/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com