【问题标题】:write getter and setter method in c# with attributes在c#中使用属性编写getter和setter方法
【发布时间】:2020-05-06 22:59:48
【问题描述】:

我有一个通用代码,我想将它用于许多字符串属性(当设置和获取这些属性时)。

像这样:(这只是一个例子)

    public class MyClass
    {
        public string MyProperty
        {
            set
            {
                 //process
            }

            get
            {
                //process
            }
        }
    }

我需要什么: 我可以将此代码编写为属性(例如:'MyCustomAttribute')并将此属性用于我需要的任何字符串属性吗?

像这样:

    public class MyClass
    {
        [MyCustomAttribute]
        public string MyProperty { set; get; }
    }


    public class MyCustomAttribute : Attribute
    {
         // do setter and getter process here (whit methods)
    }

注意:我不想写这个带有扩展的通用代码

【问题讨论】:

  • 你能从字符串派生一个类型并在那里定义流程吗?
  • 不,您需要将代码添加到每个 getter 和 setter。您可以通过添加支持字段并将功能放入 Get/Set 方法中,然后定义您的属性,例如:public string MyProperty { get => Get(backingFieldName); set => Set(backingFieldName, value); }
  • @Sami String 是一个密封类。我认为这行不通
  • @Marlonchosky 好点..

标签: c# modelattribute


【解决方案1】:

您可以在https://github.com/dotnet/roslyn/blob/master/docs/features/source-generators.cookbook.md 上查看 roslyn 的新源代码生成器功能

这将帮助您根据属性或任何其他模式自动生成属性..

【讨论】:

    猜你喜欢
    • 2016-11-30
    • 1970-01-01
    • 2019-01-07
    • 2021-08-08
    • 2012-09-16
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    相关资源
    最近更新 更多