c# – 在WinRT中,静态字段根本没有初始化

我有这样的代码
public class SomeClass
{
    private static int staticField = 10;
}

代码永远不会执行,staticField的值为0.
此外,该代码导致MVVMlight的SimpleIoc抛出异常,代码如下所示:

SimpleIoc.Default.Register<SomeClass>();

以上代码导致MVVMLight抛出异常

Cannot build instance: Multiple constructors found but none marked with PreferredConstructor.

这很奇怪
我正在使用Win8 RTM x64 VS2012 Express for Windows 8.

解决方法

这肯定是MVVMLight的SimpleIoc中的一个错误.我已经尝试过LinqPad,问题是当你添加一个静态字段到一个静态ctor由字段初始化程序添加.

结果是类SomeClass有两个用于SimpleIoc的转换,导致你描述的异常.

解决方法是将认构造函数添加到类中,并使用PreferredConstructorAttribute进行装饰,但这将导致对SimpleIoc的依赖.

其他解决方案是将静态字段更改为常量值.

public class SomeClass
{
    private const int staticField = 10;
}

或者使用Register方法的过载来提供用于实例创建的工厂方法.

SimpleIoc.Default.Register<SomeClass>(() => new SomeClass())

我已经在CodePlex上的MVVM Light项目上提交了一个bug report

LinqPad(测试代码):

void Main()
{
    var x = GetConstructorInfo(typeof(SomeClass));

    x.Dump();
    x.Isstatic.Dump();
}


public class PreferredConstructorAttribute : Attribute{

}
public class SomeClass{
  private static int staticField = 10;

}

private ConstructorInfo GetConstructorInfo(Type serviceType)
        {
            Type resolveto = serviceType;


//#if NETFX_CORE
            var constructorInfos = resolveto.GetTypeInfo().DeclaredConstructors.ToArray();
            constructorInfos.Dump();
//#else
//          var constructorInfos = resolveto.GetConstructors();
//constructorInfos.Dump();
//#endif

            if (constructorInfos.Length > 1)
            {
                var preferredConstructorInfos
                    = from t in constructorInfos
//#if NETFX_CORE
                       let attribute = t.GetCustomAttribute(typeof (PreferredConstructorAttribute))
//#else
//                     let attribute = Attribute.GetCustomAttribute(t,typeof(PreferredConstructorAttribute))
//#endif
                       where attribute != null
                       select t;

preferredConstructorInfos.Dump();

var preferredConstructorInfo = preferredConstructorInfos.FirstOrDefault ( );
                if (preferredConstructorInfo == null)
                {
                    throw new InvalidOperationException(
                        "Cannot build instance: Multiple constructors found but none marked with PreferredConstructor.");
                }

                return preferredConstructorInfo;
            }

            return constructorInfos[0];
        }
// Define other methods and classes here

问题是线

var constructorInfos = resolveto.GetTypeInfo().DeclaredConstructors.ToArray();

它返回一个具有2个ConstructorInfos的数组,它们都不使用PreferredConstructorAttribute定义,这会导致异常.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...