根据字符串类型名称动态传递类型 [英] pass a type dynamically based on string type name

查看:100
本文介绍了根据字符串类型名称动态传递类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种基于字符串类型名称将类型传递给泛型方法的方法.

例如,假设我有一个具有以下签名的方法:

I need a way to pass a type to a generic method based on a string type name.

For example, say I have a method with the following signature:

public Save<T>(Model) where T : BaseConfig, new(){}


客户端将需要根据当前下拉列表中的选择动态调用此方法.

例如,客户帐户"可能是用户选择的下拉文本,其下拉值为"ClientAccount".

基于此选择,ClientAccountConfig应该是作为T传递到保存方法的类型.

所以我需要能够实现这样的东西:


The client will need to call this method dynamically based on the selection in a current dropdown.

For example, "Client Account" might be user-selected dropdown text with a dropdown value of "ClientAccount".

Based on this selection ClientAccountConfig should be the type passed as T into the save method.

So I need to be able to implement something like this:

Type configType = typeof(ddlModule.SelectedValue.ToString() + "Config")


显然,上面的typeof将返回一个字符串,但是我正在尝试获取由我正在构建的动态字符串描述的Type对象,在这种情况下,这是ClientAccountConfig的Type对象.

你知道我怎么能做到吗?

[edit]已添加代码块,<和>转换为HTML安全版本.
请确保在粘贴时设置了转义HTML字符",或使用<"和>"文字输入框上方的效果列表中的人物.否则,当它们输出到浏览器时,它们会被HTML吞噬-这会减少或消除您的帖子感觉! -OriginalGriff [/edit]


Obviously the typeof above will return a string but I am trying to get a Type object described by the dynamic string that I''m building, in this case a Type object of ClientAccountConfig.

Do you know how I can accomplish this?

[edit]Code blocks added, < and > converted to HTML-Safe versions.
Please ensure "escape HTML characters" if set when pasting, or use the "<" and ">" characters from the effects list above the text entry box. Otherwise they get swallowed by the HTML when output to the browser - this can reduce or remove the sense of your post! - OriginalGriff[/edit]

推荐答案

您是否正在寻找这样的东西:

如果您尝试获取的Type在当前正在执行的程序集或Mscorlib.dll中,则您所需要的只是动态创建的类型名称,该名称由名称空间来限定...
Are you looking for something like this:

If the Type you are trying to get is in the currently executing assembly or Mscorlib.dll, then all you need is the dynamically created type name, qualified by the namespace...
Type configType = Type.GetType("Namespace.typeName")


如果不是,那么您将需要使用其所在的装配体来限定类型.


If not, then you will need to qualify the type with the assembly it is in...

Type configType = Type.GetType("Namespace.typeName, ExampleAssembly, Version=1.0.0.0, Culture=en, PublicKeyToken=a5d015c7d5a0b012");


这篇关于根据字符串类型名称动态传递类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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