如何检查某些字符串等于属性的“构造函数”参数? 以及如何获取所有构造函数值(TestArg1,TestArg2)?
struct MyData
{
[MyAttr("TestArg1", "TestArg2")] //check that some string equals TestArg1/TestArg2
public string TestArg;
}
答案 0 :(得分:0)
这主要取决于您要查看的属性及其编码方式。请参阅下面的代码,以获取有关如何做您所要求的内容的示例。
//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;
}
}
如您所见,我们使用反射将属性从属性中删除,然后仅比较属性。
就构造器属性而言,
typeof(MyAtt).GetConstructor().GetParameters()
将检索构造函数的参数详细信息。
Microsoft文档中也有关于此的信息:https://docs.microsoft.com/en-us/dotnet/api/system.reflection.customattributedata.constructor?view=netframework-4.7.2
答案 1 :(得分:0)
这里是您要完成的事情的一种方法,但是它不是特别可伸缩的,需要大量的手动代码才能工作,但可能会助您一臂之力。假设我们有一个类似这样的属性,它的构造函数中包含一个字符串数组:
public class MyAttrAttribute : Attribute
{
public string[] AllowedValues { get; }
public MyAttrAttribute(params string[] values)
{
AllowedValues = values;
}
}
您可以将字段更改为具有支持字段的属性。这使您可以覆盖set
方法并在那里进行检查:
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
几乎肯定比字符串更好。