gpt4 book ai didi

c# - 使用对象类型的字符串名称在 C# 中进行类型转换

转载 作者:行者123 更新时间:2023-12-02 15:16:11 25 4
gpt4 key购买 nike

我有以下代码,应该很容易理解

public class Foo
{
public void FooHasAMethod()
{
Console.WriteLine("it is me, foo!!!");
}
}

public class Bar
{
public Foo FooProperty { get; set; }
}

public class FooBar
{
public static void Main()
{
Bar bar = new Bar{ FooProperty = new Foo() };
CallPropertyByName(bar, "Foo");
}

public static void CallPropertyByName(Bar bar, string propertyName)
{
PropertyInfo pi = bar.GetType().GetProperty(propertyName + "Property");
object fooObj = pi.GetValue(bar, null);
((Foo)fooObj).FooHasAMethod(); // this works
/* but I want to use
* ((Type.GetType(propertyName))fooObj).FooHasAMethod(); This line needs fix
* which doesnt work
* Is there a way to type cast using a string name of a object?
* */
}
}

最佳答案

如果您使用 .NET 4,这实际上非常简单 =D

dynamic obj = bar;
obj.FooProperty.FooHasAMethod();

但是,如果您只想将结果转换为其他类型,则可以在运行时使用 Convert.ChangeType 方法执行此操作:

object someBoxedType = new Foo();
Bar myDesiredType = Convert.ChangeType(typeof(Bar), someBoxedType) as Bar;

现在,这个与实际类型 Foo 和 Bar 有着很强的联系。但是,您可以通用该方法来获得您想要的内容:

public T GetObjectAs<T>(object source, T destinationType)
where T: class
{
return Convert.ChangeType(typeof(T), source) as T;
}

然后,您可以像这样调用:

Bar x = GetObjectAs(someBoxedType, new Bar());

SomeTypeYouWant x = GetObjectAs(someBoxedType, Activator.CreateInstance(typeof("SomeTypeYouWant")));

使用激活器,您可以在运行时创建您想要的任何类型。并且泛型方法会被推理欺骗,尝试从 boxedType 转换为运行时类型。

此外,如果您只想对某些动态属性值调用方法,那么最佳实践(imo)就是简单地将其转换为某些所需的对象。

ISomething propValue = obj.GetProperty("FooPropery").GetValue(obj, null) as ISomething;

if(propValue != null)
propValue.FooHasAMethod();

关于c# - 使用对象类型的字符串名称在 C# 中进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5583803/

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