9

Consider the following code:

public class MyClass
{
    public MyClass(Type optionsClassType)
    {
      //A PropertyInfo[0] is returned here
      var test1 = optionsClassType.GetProperties();
      //Even using typeof
      var test2 = typeof(MyClassOptions).GetProperties();
     //Or BindingFlags
      var test3 = typeof(MyClassOptions)
          .GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public);
    }
}

public class MyClassOptions
{
    public int MyProperty { get; set; }
}

I'm unable to get PropertyInfo[] about MyClassOptions, Type.GetProperties always returns an empty array. First I thought that was a framework bug in Xamarin.iOS, but I tested the same code in another project targeting the same framework and it worked just fine.

Anyone knows possible causes for this?

EDIT

Thanks to @Fabian Bigler answer I got it. In my project, even with Linker set to a moderate behavior, instantiating MyClassOptions was not enough to keep the class definition at runtime. Only after actually using the instance(e.g. setting a property) the class is kept in my build.

Seems that linker replaces "unused" stuff with dummies. Since I'll use reflection a lot in this project I've just disabled the Linker and everything is working again.

4

1 回答 1

10

这段代码对我来说非常好:

namespace MyNameSpace
{
    public class MyClass
    {
        public MyClass(Type optionsClassType)
        {
            //A PropertyInfo[0] is returned here
            var test1 = optionsClassType.GetProperties();
            //Even using typeof
            var test2 = typeof(MyClassOptions).GetProperties();
            //Or BindingFlags
            var test3 = typeof(MyClassOptions).GetProperties
(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
        }
    }

    public class MyClassOptions
    {
        public int MyProperty { get; set; }
    }
}

BindingFlags.Instance在代码中添加。有关更多信息,请查看此帖子


然后从外部调用:

var options = new MyClassOptions();
    options.MyProperty = 1234;
    var t = options.GetType();
    var c = new MyNameSpace.MyClass(t);

注意:小心汇编链接器

如果您在启用链接器的情况下进行构建,您可能需要在某处使用该类,因此它不会在编译时被撕掉。有时,仅在代码中实例化类是不够的,链接器可能会检测到该实例从未使用过,并且无论如何都会将其删除。

于 2013-06-13T15:41:33.643 回答