繁体   English   中英

VB 到 C#:带有 Getter / Setter 的“扩展属性”

[英]VB to C#: "Extension Property" with Getter / Setter

我正在处理 VB 到 C# 的转换,我在 VB 中遇到了一个“扩展属性”(我不确定如何称呼它),我想在 C# 中复制它。

    Public Class PeopleCollection
    Inherits Dictionary(Of System.String, People)
    
    Property IfExist(ByVal name As String) As Double
        Get
            If Me.ContainsKey(name) Then
                Return Me(name).Age
            End If
        End Get
        Set(ByVal value As Double)
            If Me.ContainsKey(name) Then
                Me(name).Age = value
            End If
        End Set
    End Property
    
End Class

Public Class People
    Property Age() As Integer
    Property Name() As String
End Class

它的好处是它被称为扩展方法,但可以使用相同的名称用作 get 或 set。 它确实减少了调用方的代码。 我发现它非常有趣,希望我能在 C# 中找到一种方法。到目前为止,我找到的唯一解决方案是创建 2 个单独的方法:GetIfExists、SetIfExists,这使得它稍微不方便,并迫使我更新整个 rest 中的每个引用的代码。

谢谢您的帮助

我记得当我有一个类似的项目时使用这个工具: https://converter.telerik.com/

它产生了这个:

using System.Collections.Generic;

public class PeopleCollection : Dictionary<System.String, People>
{
    public double IfExist
    {
        get
        {
            if (this.ContainsKey(name))
                return this[name].Age;
        }
        set
        {
            if (this.ContainsKey(name))
                this[name].Age = value;
        }
    }
}

public class People
{
    public int Age { get; set; }
    public string Name { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM