c# - 如何将动态模型作为“T”传递给 C# 泛型函数
问题描述
我有一个通用函数,如下所示
private List<T> GetAll<T>()
{
var listOfTModels = // gets the list of T from the database.
return listOfTModels;
}
我需要根据将在运行时确定的字符串将模型( T )动态传递给该函数。
public void SomeFunction(string modelName)
{
// Call the above Get method with modelName parameter as the 'T'
var listOfModels = GetAll<something>(); //not sure what type this something should be "Type" or "string"
// Further Logic on listOfModels
}
怎么可能做到这一点?
解决方案
您将需要使用反射来获得这样的方法:
typeof(ClassWithGetAll).GetMethod("GetAll",
BindingFlags.Instance | BindingFlags.NonPublic);
这将返回一个方法信息,然后您将使用它来通过MakeGenericMethod
.
从字符串名称 AFAIK 获取类型的唯一方法是使用Type.GetType但您需要为此使用AssemblyQualifiedName,因此传入类似string
orint
或类似名称的短/简化名称很可能会返回null
。
如果您弄清楚如何获取限定名称或如何搜索类型,最后一件事就是调用调用MethodInfo
返回的MakeGenericMethod
内容,下面是代码外观示例:
public void SomeFunction(string modelName)
{
// No idea what the class/struct in which the method "GetAll"
// is called, hence use this name
var instance = new ClassWithGetAll();
//Retrieves the info of "GetAll<T>"
MethodInfo method = typeof(ClassWithGetAll).GetMethod("GetAll",
BindingFlags.Instance | BindingFlags.NonPublic);
//Commented out as you will need to figure out how to get the
// assembly qualified name of the input model name, unless
// it is qualified.
//modelName = GetAssemblyQualifiedName(modelName);
Type modelType = Type.GetType(modelName);
//Creates a generic method: "GetAll<T>" => "GetAll<modelType>"
method = method.MakeGenericMethod(modelType);
//Invokes the newly created generic method in the specified
// instance with null parameters, which returns List<modelType>
object list = method.Invoke(instance, null);
}
推荐阅读
- python - Tkitnter 画布小部件事件
- php - Telegram bot sendMessage parse_mode 生成 HTTP/1.1 400 错误请求
- node.js - 运行没有端口号的 Node JS 服务器
- ios - WKWebView 拦截本地文件请求
- javascript - 在某个索引处对多维数组的元素进行排序
- git - 更新 github web 中的分叉存储库以重置为原始存储库
- c# - 无法让 Intellisense 在 Ubuntu 下使用 VSCode 与 Unity 一起工作
- python - 根据 MAC 地址和用户名生成确定性 UID
- reactjs - 在 useRef 对象更新后反应组件不渲染
- javascript - 表单数据负载不适用于删除请求