gpt4 book ai didi

C# 将字符串变量转换为对象类型引用

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:23 25 4
gpt4 key购买 nike

我的 MVC5 自定义 Html 帮助程序类具有以下方法:

public static bool CheckAccessRight(this HtmlHelper htmlHelper, string Action, string Controller)
{
string displayName = GetPropertyDisplayName<Controller>(i => i.Action);
// according to logic return a bool
}

GetPropertyDisplayName 方法:

public static string GetPropertyDisplayName<T>(Expression<Func<T, object>> propertyExpression)
{
// some code
}

如您所见,GetPropertyDisplayName 方法需要一个类(类型)和类成员作为参数。

但在我的 CheckAccessRight 方法中,我只接收类名 ( string Controller ) 和成员 ( string Action ) 作为字符串。

很明显,我在这一部分遇到了错误:<Controller>(i => i.Action);

我的问题是如何将这些字符串表示形式转换为真正的类或其他解决方法。

谢谢!

最佳答案

我认为通用方法不适用于您的情况,我会解释原因。

给定一个值为类型名称的string,您可以使用以下方法获取Type 对象:

var type = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.DefinedTypes)
.Single(x => x.Name == typeName);

现在,问题来了:type 只有在运行时才知道,因为它依赖于 typeNametypeName 只有在运行时才知道.在泛型中,类型参数需要在编译时已知(在解析表达式时,其他类型参数根据给定的约束在编译时充当已知)。这就是为什么这个问题没有解决方法的原因(据我所知)。

然后,您必须求助于此的运行时解决方案。我能想到的最明显的事情是,您可以直接使用该类型并分析它提供的内容:

public static string GetPropertyDisplayName(Type type, Expression<Func<object, object>> propertyExpression)
{
// some code
}

代码根据你想从类型中提取什么信息而有所不同,但通常有方法(如GetMembers()GetMethods() GetProperties()GetCustomAttributes()) 将帮助您找到您要查找的内容。

关于C# 将字符串变量转换为对象类型引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25231182/

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