运行时和反射的初始值

本文关键字:反射的 运行时 | 更新日期: 2023-09-27 18:05:16

对于一个爱好项目,我正试图解决以下问题:我试图获得类实例在反射中也可用的初始化值。目前,我只知道如何通过使用反射属性和新的DoubleParameter(…)来设置运行时的值来做到这一点:

[MyDoubleSettings(-10,10,5)]
public DoubleParameter param2 = new DoubleParameter(-10,10,5);

我想知道是否有某种方法只在代码中有这些值一次。这个结构将被使用很多次,并且某人必然只更改其中一个。我找不到一种方法来使用反射来查看新的DoubleParameter(…)值。此外,我找不到一种方法来查看DoubleParameter类的属性。

有什么方法可以做到这一点,或者有其他一些简洁的方法来解决这个问题吗?

亲切的问候,恩斯特。

运行时和反射的初始值

您不需要属性。如果你想做的只是获取某些字段或属性的值,你可以使用Reflection轻松地做到这一点,例如,如果你有三个public属性保存这些值,你可以使用以下命令:

var values = typeof(DoubleParameter)
             .GetProperties()
             .Select(x => x.GetValue(yourInstance))
             .ToArray();

您也可以将GetValue的结果转换为double,如果您确定您的属性类型是double或根据属性类型过滤它们:

var values = typeof(DoubleParameter)
             .GetProperties()
             .Where(p => p.PropertyType == typeof(double))
             .Select(x => (double)x.GetValue(yourInstance))
             .ToArray();

回答您关于如何在属性构造函数中传递参数的问题:

(我也找不到一种方法来查看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)
    {
    }
}