Skip to main content
 首页 » 编程设计

c#之如何转换为给定类型

2024年02月06日14mq0036

我正在尝试弄清楚如何按照以下方式做某事

Type t = Type.GetType("fully qualified type name"); 
dynamic obj = foo as t 

我该怎么做?我正在查看 Convert.ChangeType(),但它只返回一个对象,这不是我想要的。

请您参考如下方法:

看来你是混科,我不明白为什么。要么使用反射,要么使用动态类型,但两者都用对我来说意义不大。

如果你正在用你控制的类型做某事,让它们实现一个接口(interface):

interface IModule 
{ 
    string Name { get; } 
} 
 
class Module1 : IModule 
{ 
    public string Name { get { return "Module 1"; } }  
} 
 
public void PrintModuleName(string moduleType) 
{ 
    Type tModule = Type.GetType("MyApp.Module1"); 
    IModule module = (IModule)Activator.CreateInstance(tModule); 
    Console.WriteLine(module.Name);  
} 

如果您正在使用您无法控制的类型,请使用 dynamic - 无需强制转换:

class Module1 
{ 
    public string Name { get { return "Module 1"; } }  
} 
 
public void PrintModuleName(string moduleType) 
{ 
    Type tModule = Type.GetType("MyApp.Module1"); 
    dynamic module = Activator.CreateInstance(tModule); 
    Console.WriteLine(module.Name);  
} 

我可以看到强制转换是必要的唯一情况是 COM 互操作作为 QueryInterface 的替代品或者如果该类型实现了一个返回新对象的转换。


关于您的评论:

Since Convert.ChangeType() returns a type of object, wouldn't obj still resolve to a type of object during runtime? How does this differ from object obj = Convert.ChangeType(foo,t);? To my understanding, the dynamic keyword still uses the same type

静态类型指定您可以在代码中访问的最受限制类型。例如,您有一个变量 t输入为 System.Type在声明中 Type t = Type.GetType("foo"); ,但在运行时,GetType将返回 System.RuntimeType 类型的值.自 System.RuntimeType继承自 System.Type , 这不是问题。

同样,一切*都继承自System.Object并且可以存储在类型为 object 的变量中.一个例子可能会有帮助:

System.Type t = Type.GetType("System.String"); 
Console.WriteLine("Runtime type of `t`:\t{0}", t.GetType().FullName); 
// Prints "Runtime type of `t` is: System.RuntimeType" 
 
System.String s = "foo"; 
Console.WriteLine("Runtime type of `s`:\t{0}", s.GetType().FullName); 
// Prints "Runtime type of `s` is: System.String" 
 
object o = s; 
Console.WriteLine("Runtime type of `o`:\t{0}", o.GetType().FullName); 
// Prints "Runtime type of `o` is: System.String" 

Dynamic 是 Reflection 的语法糖,因此不作为单独的类型存在。所以:

string s = "foo"; 
Console.WriteLine("Runtime type of `s`:\t{0}", s.GetType().FullName); 
// Prints "Runtime type of `s` is: System.String" 
 
dynamic d = s; 
Console.WriteLine("Runtime type of `d:\t{0}", d.GetType().FullName); 
// Also prints "Runtime type of `d` is: System.String" 

等同于:

string s = "foo"; 
Console.WriteLine("Runtime type of `s`:\t{0}", s.GetType().FullName); 
 
Type typeOfS = s.GetType(); 
object resultOfGetType = typeOfS.GetMethod("GetType").Invoke(s, null); 
Type typeOfResultOfGetType = resultOfGetType.GetType(); 
object resultOfFullName = typeOfResultOfGetType.GetProperty("FullName").GetValue(resultOfGetType); 
 
Console.WriteLine("Runtime type of `d:\t{0}", resultOfFullName); 

C# 仅在编译时生成所有这些代码**。

*:嗯……most everything
<子> **:嗯…… not exactly this code