gpt4 book ai didi

c# - Activator.CreateInstance() - 未找到构造函数

转载 作者:太空宇宙 更新时间:2023-11-03 15:39:17 25 4
gpt4 key购买 nike

我有以下类(class):

internal class MyQueryTranslator : ExpressionVisitor, IExpressionTranslator<QueryRequest>
{

private IReflectionManager _reflectionManager;

internal MyQueryTranslator(IReflectionManager reflectionManager)
{
this._reflectionManager = reflectionManager;
}

//....
}

与此同时,在另一个类中,我正在尝试使用 Activator.CreateInstance() 实例化此类。方法:

internal class MyPersistenceStrategy<E> : IAsyncPersistenceStrategy<E>
where E : class, IPersistableEntity
{

private IReflectionManager _reflectionManager;
private static readonly Dictionary<Type, Type> _translators;

static MyPersistenceStrategy()
{
_translators = new Dictionary<Type, Type>()
{
{ typeof(QueryRequest), typeof(MyQueryTranslator) }
}
}

private T TranslateExpression<T>(Expression expression)
{
if(_translators.ContainsKey(typeof(T))
throw new InvalidOperationException(String.Format("There is no translator for: {0}", typeof(T).Name);

IExpressionTranslator<T> translator =
(IExpressionTranslator<T>)Activator.CreateInstance(_translators[typeof(T)],
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
null,
_reflectionManager,
null);

return translator.Translate(expression);
}

//...

}

但是,我收到以下错误:

An unhandled exception of type System.MissingMethodException occured in mscorlib.dll
Additional information: Constructor on type XXXXX.MyQueryTranslator not found

如您所见,我正在传递适当的 BindingFlgs所以实际上可以找到构造函数。

TranslateExpression<T>方法是这样调用的:

QueryRequest request = TranslateExpression<QueryRequest>(expression);

我还应该注意到,这两个类都在同一个程序集中。

最佳答案

正如一些人所指出的,它匹配了错误的重载。参数必须是一个对象数组。

(IExpressionTranslator<T>)Activator.CreateInstance(_translators[typeof(T)],
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
null,
new object[] { _reflectionManager },
null);

关于c# - Activator.CreateInstance() - 未找到构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30789502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com