c# - 从属性中获取属性的名称

标签 c# asp.net asp.net-mvc asp.net-mvc-4 web

我正在使用 C# 4.5 和 ASP.NET MVC 5。 我有以下内容:

[Required(ErrorMessage = "Prop1 is required")]
public string Prop1 { get;set;}

[Required(ErrorMessage = "Prop2 is required")]
public string Prop2 { get;set;}

如您所见,错误消息是属性名称加上“是必需的”字符串。我需要的不是键入属性名称和每个属性的消息,而是使用通用方法 composer,它将返回装饰属性的名称和我添加的字符串,例如:

public string GetMessage()
{
    // Caller property should be a variable that is retrieved dynamically 
    // that holds the name of the property that called the function
    return CallerProperty + " is required";
}

所以现在我可以用户:

[Required(ErrorMessage = GetMessage())]
public string Prop2 { get;set;}

简而言之:我如何知道由属性修饰的属性名称。

最佳答案

使用反射。

public List<Required> CallerProperty<T>(T source)
{
    List<Required> result = new List<Required>();
    Type targetInfo = target.GetType();
    var propertiesToLoop = source.GetProperties();
    foreach (PropertyInfo pi in propertiesToLoop)
    {
        Required possible = pi.GetCustomAttribute<Required>();
        if(possible != null)
        {
            result.Add(possible);
            string name = pi.Name; //This is the property name of the property that has a required attribute
        }
    }
    return result;
}

这只是一个关于如何在属性上捕获自定义属性的演示。您必须弄清楚如何管理它们的列表,或者您需要什么来生成您需要的返回类型。也许将它映射到也被引用的“pi.Name”?我不知道你到底需要什么。

关于c# - 从属性中获取属性的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50734871/

相关文章:

c# - 在 asp.net 控件中,此上下文不支持代码块

asp.net - 事件示例?

c# - 如何从 FileStreamResult 获取内容

c# - 为什么带有 LINQ To SQL 和 "using"语句的 Web API Controller 不起作用?

c# - 如何使用 Roslyn 查找调用方法的参数是变量(通过 "var/string")还是内联字符串

c# - 如何使用 HttpListener 同时处理多个连接?

c# - 尝试路由到特定 URL 时找不到目录错误

c# - 请求 ["key"] 与 Request.Params ["key"] 与 Request.QueryString ["key"]

.net - ASP.Net MVC4 WebApi 代理

c# - COM 服务器如何在具有不同 ComInterfaceType 枚举的 C# 类库中编码可为空?