对于一个业余爱好项目,我试图解决以下问题:我试图获得初始化值,通过这些初始化值,类实例也可以在反射中使用。目前,我只知道如何使用反射的属性和新的DoubleParameter(...)要设置值运行时,请执行以下操作:
[MyDoubleSettings(-10,10,5)]
public DoubleParameter param2 = new DoubleParameter(-10,10,5);
我想知道是否有某种方法可以让这些值只在代码中出现一次。这个结构将会被多次使用,并且一定会有人只改变其中的一个。我找不到一种方法来使用反射来查看新的DoubleParameter(...)值。此外,我也找不到一种方法来查看DoubleParameter类的属性。
有什么方法可以做到这一点吗?或者有没有其他更好的方法来解决这个问题?
温馨问候,恩斯特。
发布于 2014-05-27 19:38:23
您不需要attribute.If,您所要做的就是获取某些字段或属性的值,您可以使用Reflection
轻松实现这一点,例如,如果您有三个包含这些值的公共属性,您可以使用以下方法:
var values = typeof(DoubleParameter)
.GetProperties()
.Select(x => x.GetValue(yourInstance))
.ToArray();
如果您确定属性的类型为double
,也可以将GetValue
的结果强制转换为double
,或者根据属性类型对其进行过滤:
var values = typeof(DoubleParameter)
.GetProperties()
.Where(p => p.PropertyType == typeof(double))
.Select(x => (double)x.GetValue(yourInstance))
.ToArray();
发布于 2014-05-27 19:53:55
要回答有关如何在属性构造函数中传递参数的问题:
(我也找不到从DoubleParameter类中查看属性的方法)
class Program
{
static void Main(string[] args)
{
TestClass _testClass = new TestClass();
Type _testClassType = _testClass.GetType();
// Get attributes:
// Check if the instance class has any attributes
if (_testClassType.CustomAttributes.Count() > 0)
{
// Check the attribute which matches TestClass
CustomAttributeData _customAttribute = _testClassType.CustomAttributes.SingleOrDefault(a => a.AttributeType == typeof(TestAttribute));
if (_customAttribute != null)
{
// Loop through all constructor arguments
foreach (var _argument in _customAttribute.ConstructorArguments)
{
// value will now hold the value of the desired agrument
var value = _argument.Value;
// To get the original type:
//var value = Convert.ChangeType(_argument.Value, _argument.ArgumentType);
}
}
}
Console.ReadLine();
}
}
[TestAttribute("test")]
public class TestClass
{
}
public class TestAttribute : System.Attribute
{
public TestAttribute(string _test)
{
}
}
https://stackoverflow.com/questions/23888273
复制相似问题