简体   繁体   English

有没有办法枚举类中的所有静态函数?

[英]Is there a way to enumerate all the static functions in a class?

I have a class with lots of static methods, which I am using it as a sort of style sheet. 我有一个带有很多静态方法的类,我将它用作一种样式表。

You give one of its methods a Label and it sets a bunch of the label properties such as color, font family and font size. 您给它的一种方法指定了Label,它设置了一堆标签属性,例如颜色,字体系列和字体大小。

I want to create a page where you can view all the different Label styles so I would like to enumerate these static methods so I can apply each one to a label. 我想创建一个页面,您可以在其中查看所有不同的Label样式,因此我想列举这些静态方法,以便可以将每个方法应用于标签。

Is this possible? 这可能吗? Is there a better way to template object properties? 有没有更好的模板对象属性的方法?

public static class Palette
{

    public static class LabelStyle
    {

        public static void H3 (ref Label label)
        {
            label.TextColor     = Xamarin.Forms.Color.White;
            label.FontFamily    = "Myriad";
            label.FontSize      = 14;
        }

        public static void H4 (ref Label label)
        {
            if (Device.OS == TargetPlatform.iOS) 
            {
                label.FontFamily = Device.OnPlatform ("Myriad Pro", null, null);
            } 
            else
            {
                label.FontFamily = "Myriad";
            }

            label.TextColor     = Color.BlueBlack;
            label.FontSize      = 14;
        }

        ...
  }
  ...
}

Reflection is the key word here. 反思是这里的关键词。

typeof(Palette.LabelStyle).GetMethods(BindingFlags.Static)

It can also be used for various similar purposes. 它也可以用于各种相似的目的。

You may have to choose appropriate binding flags. 您可能必须选择适当的绑定标志。 In this example BindingFlags.Static is there to enumerate static methods. 在此示例中, BindingFlags.Static用来枚举静态方法。 You need another binding flag for non-public ones. 对于非公共标记,您需要另一个绑定标记。 That would be: 那将是:

BindingFlags.Static | BindingFlags.NonPublic

for example. 例如。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM