c# - 从静态方法访问隐藏属性

标签 c#

鉴于以下

class BaseClass
{
    public int Property {get; protected set;}
}

class DerivedClass : BaseClass
{
    public new int Property {get; set;} //Hides BaseClass.Property

    public static DerivedClass Build()
    {
         var result = new DerivedClass
         {
              Property = 17;
              //base.Property = 17; // this doesn't compile
         }
         //((BaseClass)result).Property = 17; // this doesn't compile
    }
}

有什么方法可以从 DerivedClass 中的静态方法设置 BaseClass.Property。

反射或不安全代码不是我想要的!我想要一种非骇人听闻的方式来设置我们合法有权访问的内容,但我不知道如何设置。

最佳答案

以下是如何从类的静态方法访问重写的属性:

  1. 向类添加一个访问基本属性的新属性:

    private double BaseProperty { get => base.MyProperty; set => base.MyProperty = value; }
    
  2. 使用静态中的新属性:

    var result = new DerivedClass
    {
        BaseProperty = 17;
    }
    

在这种情况下,上述技术是我找到的最干净的解决方案。
考虑在类库中引用 BindableProperty 的 XAML。
(在我的例子中,类库是 Xamarin Forms。)

在不更改属性名称的情况下,我想将基本属性(由编译到库中的代码使用)与 XAML 可见属性(在我的子类中)分离。
具体用途是使文本自动适应,X-Forms 尚不支持。

此处相关的细节是我有以下 BindableProperty 声明:

public new static readonly BindableProperty FontSizeProperty =
    BindableProperty.Create("FontSize", typeof(double), typeof(AutofitLabel), -1.0,
        propertyChanged: (BindableObject bindable, object oldValue, object newValue) => {
            ((AutofitLabel)bindable).BaseFontSize = (double)newValue;
        });

它使用这个私有(private)属性:

private double BaseFontSize { get => base.FontSize; set => base.FontSize = value; }

这完成的是最初将 base.FontSize 设置为 XAML 中设置的值,字体大小将由库的 Label 或其他包含文本的 View 中的布局逻辑使用。在我的子类的其他地方,一旦知道可用的宽度/高度,我就有根据需要降低 base.FontSize 的逻辑。

这种方法可以在不更改其源代码的情况下使用该库,同时让我的子类的客户看到自动适配是内置的。
更改客户端代码可见的 FontSize 是无效的 - 它表示请求的大小。 However, that is the approach taken by Charles Petzold in XF Book Ch. 5 "EmpiricalFontSizePage" .此外,Petzold 让页面本身处理自动调整大小——这并不方便。

挑战在于需要告诉库要使用的实际 FontSize。 因此这个解决方案。

我在网上找到的所有其他方法都需要复杂的自定义渲染器,复制 XF 库中已有的逻辑。

关于c# - 从静态方法访问隐藏属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53102009/

相关文章:

c# - 列出从 child 到 parent 的分配

c# - LiteDB:字段 'Null' 上的 BSON 数据类型 '_id' 无效

c# - 单击用户控件时如何防止窃取焦点?

c# - 如何使用 T 参数评估其类型 c#

c# - 如何获取PDF页面的宽度和高度?

c# - SQL:按顺序对 VarBinary 列执行 UPDATE .WRITE

c# - HttpClient未在.Net Core 3.1中发送授权承载 token

c# - 如果验证中有任何错误,请禁用提交按钮

C# getters, setters 声明

c# - 如何调试这个或可能的原因? Moq.Verify 上的用户代码未处理 System.NullReferenceException