1

我有一个这样设置的课程:

public class Strategy
{
    public readonly string Name;
    public readonly int Age;

    public Strategy(string Name, int Age)
    {
        this.Name = Name;
        this.Age = Age;
    }

    public static readonly Strategy CoolStrategy = new Strategy("Super Awesome", 24);
    public static readonly Strategy LameStrategy = new Strategy("Work Harder!", 14);
}

我希望能够使用反射来使用扩展,我可以这样说:

Strategy[] CurrentStrategies = typeof(Strategy).GetStaticInstances<Strategy>();

然后,当我在此类中添加更多静态策略时,此扩展将返回它们的数组。所以在这种情况下,它将返回一个包含 CoolStrategy 和 LameStrategy 的数组。

这将允许我将实例添加到类中,并在其他地方获得数组。

有任何想法吗?

4

3 回答 3

2

The way I understand your question, you want to get values of all public static fields of a given type. The following method does exactly that:

public static IEnumerable<T> GetStaticInstances<T>()
{
    Type typeOfInstance = typeof(T);

    IEnumerable<T> instances = typeOfInstance
        .GetFields(BindingFlags.Public | BindingFlags.Static)
        .Where(field => field.FieldType == typeOfInstance)
        .Select(field => (T)field.GetValue(null));

    return instances;
}

However, wouldn't it be sufficient to simply include a method in the Strategy class that would return all available strategies? If you'll want to add a new strategy in the future, you would simply add it to that method.

于 2012-07-14T18:46:45.123 回答
0
public static class StrategyExtensions
{
    public static Strategy[] GetAllStrategies()
    {
        var statics = typeof (Strategy).GetFields(BindingFlags.Static | BindingFlags.Public);
        var strategies = statics.Where(f => f.FieldType == typeof (Strategy));
        var values = strategies.Select(s => s.GetValue(null));
        return values.Cast<Strategy>().ToArray();
    }
}

然后

var all = StrategyExtensions.GetAllStrategies();
foreach (var strategy in all)
    Console.WriteLine("name: {0} age: {1}", strategy.Name, strategy.Age);
于 2012-12-01T22:32:24.080 回答
0

不太确定你在问什么;但听起来你想检查 FieldInfo.FieldType 而不是 GetValue ......

于 2012-07-13T18:22:44.790 回答