我有这样的代码
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定义,这会导致异常.