9

我有这样的代码

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.

这非常离奇。我正在为 Windows 8 使用 Win8 RTM x64 + VS2012 Express。

4

1 回答 1

12

这绝对是 MVVMLight 的 SimpleIoc 中的一个 bug。我已经用 LinqPad 尝试过,问题是当你向类添加一个静态字段时,字段初始化程序会添加一个静态 ctor。

结果是 SomeClass 类有两个用于 SimpleIoc 的 ctor,这会导致您描述的异常。

一种解决方法是向类添加一个默认构造函数并用 装饰它,PreferredConstructorAttribute但这将导致对 SimpleIoc 的依赖。

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

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

或者使用 Register 方法的重载来为实例创建提供工厂方法。

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

我已经在 CodePlex 上提交了一份关于 MVVM Light 项目的错误报告

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 的数组,这两个 ConstructorInfos 均未定义导致异常的 PreferredConstructorAttribute。

于 2012-11-08T08:38:01.037 回答