【问题标题】:Function in a static C# class that can return the values of all of its public member variables [duplicate]静态 C# 类中的函数,可以返回其所有公共成员变量的值 [重复]
【发布时间】:2023-01-27 01:58:53
【问题描述】:
internal static class Items
{
    public static string ItemOne = "test";
    public static string ItemTwo = "test two";
    public static string ItemThree = "test three";        

    public static List<string> GetItemsValuesList()
    {

        // some code that can gather the values of all the member variables


        return new List<string>();
    }
}

我已经在 SO 上看到了其他一些问题,但就我而言,我正在上静态课。如何通过GetItemsValuesList()方法返回包含所有成员变量的所有值的列表?

【问题讨论】:

  • 你问的是如何给 List&lt;&gt; 添加值?如何使用反射从任何给定类动态获取属性?还有别的吗?
  • 这个能够完成了,但是您有什么理由不将这些值存储在 Dictionary 中吗? (顺便说一句,我想你要么希望这些值是const,要么让它们成为属性,因为它们是全局变量,任何人都可以随意调整,这对可维护性非常不利。)

标签: c# static-classes


【解决方案1】:

尝试这个,

using System;
using System.Collections.Generic;
using System.Reflection;

public static class MyStaticClass
{
    public static int MyInt = 1;
    public static string MyString = "hello";
    public static bool MyBool = true;
}

public static class MyStaticHelper
{
    public static List<object> GetAllValues()
    {
        List<object> values = new List<object>();
        Type type = typeof(MyStaticClass);
        FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);
        foreach (FieldInfo field in fields)
        {
            values.Add(field.GetValue(null));
        }
        return values;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-12
    • 2016-11-14
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多