生成特定构造函数重载调用的编译时错误

huangapple go评论69阅读模式
英文:

Generate compile-time error for a particular constructor overload invocation

问题

是否可以在整个解决方案中的任何地方访问构造函数的特定重载时,生成编译时警告/错误?

详细信息

这是一个WPF桌面(.NET 7)项目。我的页面和用户控件使用 d:DataContext="{d:DesignInstance Type=vm:UnderlyingVM}" 功能来利用设计时智能感知。然而,底层的 VM 需要在它们的构造函数中传递外部服务(标准 IoC/DI 部分),而设计师只能调用无参数构造函数。

为了解决这个问题,我在每个 VM 中定义了无参数构造函数的重载。这些重载的唯一目的和用途是设计时支持,不能在任何其他地方无意中调用这些重载。是否有一种方法可以在常规代码中发现这种调用时生成编译时警告/错误?

我考虑的一种方法是在无参数构造函数中使用以下代码:

if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
  #error ("此构造函数只能从 WPF 设计器中调用。");
}

不幸的是,VM 层是一个 .NET Standard 2.0 项目,因此无法引用 .NET 6/7 组件。是否有人能提出替代方法?

英文:

Is it possible to generate a compile-time warning/error if a particular overload of the constructor is accessed anywhere in entire solution?

Detail

This is a WPF desktop (.NET 7) project. My Pages and UserControls use d:DataContext="{d:DesignInstance Type=vm:UnderlyingVM}" feature to take advantage of design-time intellisense. However, the underlying VMs require passing in external services (standard IoC/DI stuff) in their constructors, while the designer can invoke parameter-less constructors only.

To get around this problem, I have defined parameter-less constructor overloads in each VM. Sole purpose and usage of these overloads is the designer support and these overloads must not inadvertently be called from anywhere else. Is there a way to generate a compile-time warning/error if such an invocation is found anywhere in the regular code?

One approach that I thought of was use the following in the parameter-less constructor:

if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
  #error ("This constructor can only be invoked from the WPF designer.");
}

Unfortunately, the VM layer is a .NET Standard 2.0 project and therefore cannot reference .NET 6/7 assemblies. Can anyone suggest an alternate approach?

答案1

得分: 4

你可以使用 ObsoleteAttribute

public class Example
{
   [Obsolete("此构造函数应仅由 WPF 设计器使用")]
   public Example()
   {
   }
}

默认情况下,如果你调用带有此属性的方法,你将收到编译器警告。

英文:

You could use the ObsoleteAttribute:

public class Example
{
   [Obsolete("this constructor should only be used by the WPF designer")]
   public Example()
   {
   }
}

By default, if you call a method with this attribute, you will get a compiler warning.

huangapple
  • 本文由 发表于 2023年7月10日 16:41:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76652096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定