如何检查某个字符串是否等于属性的“构造函数”参数?如何获取所有的构造器值(TestArg1,TestArg2)?
struct MyData
{
[MyAttr("TestArg1", "TestArg2")] //check that some string equals TestArg1/TestArg2
public string TestArg;
}
发布于 2018-12-18 05:03:02
这主要取决于您正在查看的属性以及它的编码方式。请看下面的代码,作为如何执行您所要求的操作的示例。
//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()
将检索构造函数的参数详细信息。
在微软文档中也有关于这方面的信息:https://docs.microsoft.com/en-us/dotnet/api/system.reflection.customattributedata.constructor?view=netframework-4.7.2
发布于 2018-12-18 05:08:46
这里有一种方法可以做你想要的,但它不是特别可伸缩的,并且需要一堆手动代码才能工作,但可能会让你走上你想要实现的道路。假设我们有一个这样的属性,它的构造函数中有一个字符串数组:
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
几乎肯定是比string更好的选择。
https://stackoverflow.com/questions/53822797
复制相似问题