首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C#属性检查是一个等于构造函数参数和获取构造函数值的值

C#属性检查是一个等于构造函数参数和获取构造函数值的值
EN

Stack Overflow用户
提问于 2018-12-18 04:50:05
回答 2查看 550关注 0票数 0

如何检查某个字符串是否等于属性的“构造函数”参数?如何获取所有的构造器值(TestArg1,TestArg2)?

代码语言:javascript
复制
struct MyData
{
    [MyAttr("TestArg1", "TestArg2")] //check that some string equals TestArg1/TestArg2
    public string TestArg;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-18 05:03:02

这主要取决于您正在查看的属性以及它的编码方式。请看下面的代码,作为如何执行您所要求的操作的示例。

代码语言:javascript
复制
//The attribute we're looking at
public class MyAtt : System.Attribute
{
    public string name;
    public string anotherstring;

    public MyAtt(string name, string anotherstring)
    {
        this.name = name;
        this.anotherstring = anotherstring;
    }
}

public static class Usage
{
    [MyAtt("String1", "String2")] //Using the attribute
    public static string SomeProperty = "String1";
}

public static class Program
{
    public static void Main()
    {
        Console.WriteLine(IsEqualToAttribute("String1"));
        Console.WriteLine(IsEqualToAttribute("blah"));
        Console.ReadKey();
    }

    public static bool IsEqualToAttribute(string mystring)
    {
        //Let's get all the properties from Usage
        PropertyInfo[] props = typeof(Usage).GetProperties();
        foreach (var prop in props)
        {
            //Let's make sure we have the right property
            if (prop.Name == "SomeProperty")
            {
                //Get the attributes from the property
                var attrs = prop.GetCustomAttributes();

                //Select just the attribute named "MyAtt"
                var attr = attrs.SingleOrDefault(x => x.GetType().Name == "MyAtt");
                MyAtt myAttribute = attr as MyAtt; //Just casting to the correct type
                if (myAttribute.name == mystring) //Compare the strings
                    return true;
                if (myAttribute.anotherstring == mystring) //Compare the strings
                    return true;
            }
        }

        return false;
    }
}

正如您所看到的,我们使用反射从属性中获取属性,然后只比较属性。

更多信息可在此处找到:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/accessing-attributes-by-using-reflection

就获取构造函数属性而言,如下所示

代码语言:javascript
复制
typeof(MyAtt).GetConstructor().GetParameters()

将检索构造函数的参数详细信息。

在微软文档中也有关于这方面的信息:https://docs.microsoft.com/en-us/dotnet/api/system.reflection.customattributedata.constructor?view=netframework-4.7.2

票数 0
EN

Stack Overflow用户

发布于 2018-12-18 05:08:46

这里有一种方法可以做你想要的,但它不是特别可伸缩的,并且需要一堆手动代码才能工作,但可能会让你走上你想要实现的道路。假设我们有一个这样的属性,它的构造函数中有一个字符串数组:

代码语言:javascript
复制
public class MyAttrAttribute : Attribute
{
    public string[] AllowedValues { get; }
    public MyAttrAttribute(params string[] values)
    {
        AllowedValues = values;
    }
}

您可以将字段更改为具有支持字段的属性。这允许您覆盖set方法并在其中执行检查:

代码语言:javascript
复制
private string _testArg;

[MyAttr("TestArg1", "TestArg2")] //check that some string equals TestArg1/TestArg2
public string TestArg
{
    get => _testArg;

    set
    {
        var allowedValues = this.GetType() //Get the type of 'this'
            .GetProperty(nameof(TestArg)) // Get this property
            .GetCustomAttribute<MyAttrAttribute>() // Get the attribute
            .AllowedValues; //Get the allowed values specified in the attribute

        if(!allowedValues.Contains(value))
        {
            throw new ArgumentOutOfRangeException(nameof(value), 
                $"The value '{value}' is not allowed");
        }
        _testArg = value;
    }
}

说了这么多,我坚信有更好的方法来实现你所要求的。例如,如果您只能使用最小的值集,那么enum几乎肯定是比string更好的选择。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53822797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档