gpt4 book ai didi

c# - 将动态加载类型传递给 SomeFunction

转载 作者:行者123 更新时间:2023-11-30 16:27:49 28 4
gpt4 key购买 nike

我正在尝试传递一个动态加载的 dll 的类型(它使用一个接口(interface),但我需要conectrete implementation of this) to a function and am missing something.

var data = LoadAssemblyFromParamenter(pathToDataDll);
Type dataType = data.GetType().MakeGenericType(data.GetType());
SomeTest<dataType>();

public void SomeTest<T>()
{
//do something with T
}

错误是“找不到类型或命名空间‘dataType’...”

具体类型用于 FileHelpers 对象(使用字段),因此我需要具体实现。

附注这必须是 .net 3.5 ....

详细说明 SomeMethod<T>( IEnumerable<T> items )通话

public static void WriteRecords<T>(IEnumerable<T> records, string fileName )
where T: ICMSDataDictionary
{
if (records == null || String.IsNullOrEmpty(fileName))
return;

if (records.Any())
{
FileHelpers.DelimitedFileEngine<T> engine =
new FileHelpers.DelimitedFileEngine<T>();
engine.WriteFile(fileName, records);
}
}

最佳答案

您不能使用 Method 语法执行此操作,因为为此您会在编译时知道类型。但是,您可以使用反射调用您的方法。

此代码应该可以帮助您开始:

    static void Main(string[] args)
{
//Get method Method[T]
var method = typeof(Program).GetMethod("Method", BindingFlags.NonPublic | BindingFlags.Static);
//Create generic method with given type (here - int, but you could use any time that you would have at runtime, not only at compile time)
var genericMethod = method.MakeGenericMethod(typeof(int));
//Invoke the method
genericMethod.Invoke(null, null);
}

static void Method<T>()
{
Console.WriteLine(typeof(T).Name);
}

对于对象,它是相似的,但是你必须动态地构造对象,使用反射。

关于c# - 将动态加载类型传递给 SomeFunction<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7556264/

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