简体   繁体   English

在 c# 中使用属性编写 getter 和 setter 方法

[英]write getter and setter method in c# with attributes

I have a general code that i want using it for many string properties (when these properties set and get).我有一个通用代码,我想将它用于许多字符串属性(当这些属性设置和获取时)。

like this: (this is just an example)像这样:(这只是一个例子)

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

            get
            {
                //process
            }
        }
    }

What I need: Can i write this code as attribute (For exmple: 'MyCustomAttribute') and just using this attribute for any string property that i need?我需要什么:我可以将此代码编写为属性(例如:'MyCustomAttribute')并将此属性用于我需要的任何字符串属性吗?

like this:像这样:

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


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

Note: I dont want write this general code with extensions注意:我不想用扩展编写这个通用代码

You may have a look on the new source generators feature of roslyn at https://github.com/dotnet/roslyn/blob/master/docs/features/source-generators.cookbook.md您可以在https://github.com/dotnet/roslyn/blob/master/docs/features/source-generators.cookbook.md中查看 roslyn 的新源生成器功能

This will help you auto generate properties based on attributes or any other pattern..这将帮助您根据属性或任何其他模式自动生成属性。

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

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