以下面的课程为例:
class Sometype
{
int someValue;
public Sometype(int someValue)
{
this.someValue = someValue;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我想使用反射创建这种类型的实例:
Type t = typeof(Sometype);
object o = Activator.CreateInstance(t);
Run Code Online (Sandbox Code Playgroud)
通常这会起作用,但是由于SomeType没有定义无参数构造函数,调用Activator.CreateInstance将抛出类型异常,MissingMethodException并带有消息" 没有为此对象定义无参数构造函数. "是否还有另一种方法可以创建此类型的实例?将无参数构造函数添加到我的所有类中会有点麻烦.
我正在尝试模拟我正在使用的第三方接口(EventStore ClientAPI/IEventStoreConnection),特别是这个方法:
Task<StreamEventsSlice> ReadStreamEventsForwardAsync(string stream, long start, int count, bool resolveLinkTos, UserCredentials userCredentials = null);
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是返回类型StreamEventsSlice有readonly字段和internal构造函数,即
public class StreamEventsSlice
{
public readonly string Stream;
//other similar fields
internal StreamEventsSlice(string stream) //missing other fields
{
Stream = stream;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的测试代码中,我正在使用 模拟事件存储连接Moq,设置ReadStreamEventsForwardAsyncMethod,并尝试像这样设置返回类型:
var connection = new Mock<IEventStoreConnection>();
connection.Setup(s => s.ReadStreamEventsForwardAsync(It.IsAny<string>(), It.IsAny<long>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<UserCredentials>())
.ReturnsAsync(new StreamsEventSlice { props here });
Run Code Online (Sandbox Code Playgroud)
但是我不能设置属性,或者调用构造函数而不是那个(我实际上只需要设置两个属性)
我尝试制作一个扩展原始类的存根,然后返回它。虽然我可以隐藏只读属性,但我在类上收到错误消息,提示“StreamEventsSlice 没有采用 0 个参数的构造函数”。给它一个构造函数是行不通的,因为我不能调用基本构造函数,因为它是内部构造函数。
当我无法实例化返回类型时,如何模拟接口上的方法?