【问题标题】:Unable to Call GetType() on Static Class无法在静态类上调用 GetType()
【发布时间】:2017-02-16 06:31:05
【问题描述】:

我在NewStarterTool 命名空间中有以下Globals 类:

static class Globals
{
    static internal class FieldNames
    {
        public const string FirstName = "FirstName";
        public const string MiddleInitial = "_3f304008_6d27_46e4_82e1_81d2ea5d5d84";
        public const string LastName = "__x007b_39b5c34f_247a_466c_8a76_480f54461087_x007d_";
        public const string Role = "__x007b_c0bc5325_2cdb_4b7d_8687_eba9cf958f01_x007d_";
        public const string Department = "Department";
        public const string JobTitle = "JobTitle";
        public const string Office = "_38bb16d7_d38b_4409_aa54_25bd0cb921af";
        public const string ReportingTo = "_398dc3c8_ff1d_4013_a6e0_139809b37b0d";
        public const string SecretaryTo = "_cefdf77c_5767_4539_aa5b_098aa3ff0b60";
        public const string StartDate = "StartDate";
        public const string FullTime = "_96d926ba_0a82_4773_964a_43d884e5d6d4";
    }
}

在同一个命名空间中,我有一个WPF 表单,我希望Initialise() 方法在其中迭代从SharePoint 检索到的每个项目的所有FieldNames 属性:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        Initialise();
        InitializeComponent();
    }

    private void Initialise()
    {
        var siteUrl = "http://MySharePointSite/SubSiteName/";
        var listName = "TestList";
        var camlQuery = "<View Scope='RecursiveAll'></View>";

        var listItemCollection = SharePoint.GetListItems(siteUrl, listName, camlQuery);

        foreach (var item in listItemCollection)
        {
            foreach (var property in Globals.FieldNames.GetType().GetProperties())
            {

            }
        }
    }
}

但是,在foreach (var property in Globals.FieldNames.GetType().GetProperties()) 线上,我看到了这个错误:

非静态字段、方法或属性“object.GetType()”需要对象引用

尽管我可以看到 GlobalsFieldNames 都是静态的,因此不应导致此错误。


我可以确认这没有任何问题:

var dept = Globals.FieldNames.Department;

我尝试将FieldNames 更改为:

public static class FieldNames

我也尝试将方法签名更改为:

private static void Initialise()

但两者的结果相同。


为什么会这样?

如何遍历FieldNames 的属性?

【问题讨论】:

标签: c# oop static compiler-errors


【解决方案1】:

排队

foreach (var property in Globals.FieldNames.GetType().GetProperties())

您将FieldNames 视为具有方法调用的对象,并且没有静态方法FieldNames.GetType()

但你可以使用

foreach (var property in typeof(Globals.FieldNames).GetProperties())

改为。

【讨论】:

    【解决方案2】:

    首先,您的类是静态的,GetTypes() 是一个实例成员。

    如前所述,您可以使用typeof(Globals.FieldNames).GetProperties()

    除非那也行不通,因为您没有属性。您感兴趣的值都是字段。

    所以你需要typeof(Globals.FieldNames).GetFields()

    然后您可以从每个 FieldInfo 中获取 (string) field.GetValue(null) 的值。

    【讨论】:

      猜你喜欢
      • 2012-04-24
      • 1970-01-01
      • 2010-10-30
      • 2011-07-21
      • 2011-12-11
      • 2012-11-29
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      相关资源
      最近更新 更多