【问题标题】:Instantiating class with NO constructor results in 'does not contain constructor which takes 0 arguments' error使用 NO 构造函数实例化类会导致“不包含采用 0 个参数的构造函数”错误
【发布时间】:2021-10-16 22:03:54
【问题描述】:

我正在尝试从 Azure.Search.Documents 库中实例化 FacetResult

var facetResult = new Azure.Search.Documents.Models.FacetResult(); 

VS 告诉我该类不包含零参数的构造函数。当我检查类的元数据时 - 没有构造函数。

查看the docs for the class 似乎可以确认没有构造函数——那么问题出在哪里?

I'm having the same issue with other library classes with no constructors such as Azure.Storage.Blobs.Models.BlobItem, while classes which appear to explicitly declare a parameterless constructor seem fine, such as System.Exception

对此的任何帮助将不胜感激,它会阻止我的单元测试!

【问题讨论】:

  • 基类ctor至少需要一个参数
  • 您的标题是“继承自...的类”。我在您显示的代码中看不到任何继承
  • 总有一个构造函数。如果源代码中没有,编译器会自动创建一个无参数构造函数。
  • github 文档显示构造函数是internalgithub repo docs
  • 当您在new FacetResult( 中键入左括号时,Intellisense 会做什么?它是否建议您可以在没有参数的情况下关闭它,是否给您任何提示?你看过类元数据吗?也许有类似internal 构造函数的东西,只允许在同一程序集中定义的对象实例创建其中一个(毕竟它是Result

标签: c# visual-studio constructor azure-cognitive-search


【解决方案1】:

此类的构造函数是内部的。 实例很可能是由工厂创建和返回的。

//src code @ https://github.com/Azure/azure-sdk-for-net/
namespace Azure.Search.Documents.Models
{
    /// <summary> A single bucket of a facet query result. Reports the number of documents with a field value falling within a particular range or having a particular value or interval. </summary>
    public partial class FacetResult
    {
        /// <summary> Initializes a new instance of FacetResult. </summary>
        internal FacetResult()
        {
            AdditionalProperties = new ChangeTrackingDictionary<string, object>();
        }

        /// <summary> Initializes a new instance of FacetResult. </summary>
        /// <param name="count"> The approximate count of documents falling within the bucket described by this facet. </param>
        /// <param name="additionalProperties"> Additional Properties. </param>
        internal FacetResult(long? count, IReadOnlyDictionary<string, object> additionalProperties)
        {
            Count = count;
            AdditionalProperties = additionalProperties;
        }

https://github.com/Azure/azure-sdk-for-net/blob/4162f6fa2445b2127468b9cfd080f01c9da88eba/sdk/search/Azure.Search.Documents/src/Generated/Models/FacetResult.cs

【讨论】:

  • 那就这样吧,谢谢。我无法从 VS 中的元数据或 MSDN 文档中收集到这一点——以后我一定会检查 github。干杯@lidqy。
  • 您仍然可以使用反射创建它。只是似乎带有 2-3 个属性作为一种 poco,没有隐藏逻辑。
  • 如果有人出于与我提出问题完全相同的原因来到这里,实例化或模拟 FacetResult 以进行测试,请查看专为此目的设计的 SearchModelFactory:azuresdkdocs.blob.core.windows.net/$web/dotnet/…
猜你喜欢
  • 1970-01-01
  • 2013-02-16
  • 2011-11-06
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
相关资源
最近更新 更多