创建一个没有构造函数的类的实例?

时间:2014-03-14 12:59:40

标签: c# windows-phone-8

我的应用是使用语音识别库的Windows Phone 8应用。该类中的一种对象类型是 SpeechRecognitionResult 。这个类没有构造函数或者它们是内部的。我想创建一个这种类型的对象,这样我就可以从我的视图模型中属性 SpeechRecognitionResult 的属性返回设计时数据。我发现这个SO帖子似乎有一个解决方案:

Creating instance of type without default constructor in C# using reflection

但我无法在任何地方找到 FormatterServices 符号,因此我可以调用 FormatterServices.GetUninitializedObject()。我的代码文件中包含 System.Reflection 和“System.Runtime.Serialization”。有谁知道我在WP8项目中可以找到哪种方法?如果没有,还有另一种方法可以完成这项工作吗?

2 个答案:

答案 0 :(得分:1)

您可以使用反射来检索内部/私有构造函数,并调用它。这是另一个问题,如果你应该这样做,因为构造函数是内部/私人的原因,这通常意味着你不应该这样做。

public class TestClass {
    private TestClass() { }
}

var t = typeof(TestClass);
var ci = t.GetConstructor(
    BindingFlags.NonPublic | BindingFlags.Instance,
    null,
    new Type[0],
    null
);
var myTestClassObject = (TestClass)ci.Invoke(null);

答案 1 :(得分:1)

很多时候,当课程没有构造函数时,他们并不打算直接创建。对于SpeechRecognitionResult对象,这些对象是对RecognizeSpeechToTextAsync的调用的结果。你可以在网上找到例子,但一个简单的例子是:

var credentials = new SpeechAuthorizationParameters();
credentials.ClientId = "<YOUR CLIENT ID>";
credentials.ClientSecret = "<YOUR CLIENT SECRET>";
var sr = new SpeechRecognizer("en-US", credentials);

var speechResult = await sr.RecognizeSpeechToTextAsync();

在这个例子中&#34; speechResult&#34;属于&#34; SpeechRecognitionResult&#34;。从那里你应该能够序列化&#34; Text&#34;或备用版本属性,并使用前端的那些。希望这有助于您走上正确的轨道!

如果您需要更多详细信息,请reference MSDN here