我想实现一个带有以下签名的方法
dynamic Cast(object obj, Type castTo);
Run Code Online (Sandbox Code Playgroud)
谁知道怎么做?obj肯定实现了castTo,但是需要正确地进行转换才能使我的应用程序的运行时绑定工作得以实现.
编辑:如果一些答案没有意义,那是因为我最初不小心输入dynamic Cast(dynamic obj, Type castTo);- 我的意思是输入应该是object或其他一些保证基类
我有以下代码:
public class ClassExample
{
void DoSomthing<T>(string name, T value)
{
SendToDatabase(name, value);
}
public class ParameterType
{
public readonly string Name;
public readonly Type DisplayType;
public readonly string Value;
public ParameterType(string name, Type type, string value)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
if (type == null)
throw new ArgumentNullException("type");
this.Name = name;
this.DisplayType = type;
this.Value = value;
}
}
public void GetTypes()
{
List<ParameterType> l = report.GetParameterTypes();
foreach (ParameterType p in l)
{
DoSomthing<p.DisplayType>(p.Name, (p.DisplayType)p.Value);
}
}
} …Run Code Online (Sandbox Code Playgroud) 我曾经使用下面的代码将JSON文本反序列化为强类型对象
Trainer myTrainer = JsonConvert.DeserializeObject<Trainer>(sJsonText);
Run Code Online (Sandbox Code Playgroud)
现在我需要将反序列化JSON文本转换为特定类型,只知道类型的名称.
我尝试使用Reflection从其名称中获取Type,然后将此类型与JsonConvert一起使用,如下所示:
Type myType = Type.GetType("Trainer");
var jobj = JsonConvert.DeserializeObject<myType >(sJsonText);
Run Code Online (Sandbox Code Playgroud)
但不幸的是,下面的错误显示出来:
CS0118 'myType' is a variable but is used like a type
Run Code Online (Sandbox Code Playgroud)
有没有办法可以使用字符串引用类?