gpt4 book ai didi

c# - 有没有办法在 C# 中通过代码重用来实现多个属性?

转载 作者:太空狗 更新时间:2023-10-29 23:06:42 25 4
gpt4 key购买 nike

我有一个类似这样的类:

public class Abc
{
public string City
{
get { return _getValue(); }
set { _setValue(value); }
}
public string State
{
get { return _getValue(); }
set { _setValue(value); }
}
private string _getValue()
{
// determine return value via StackTrace and reflection
}
...
}

(是的,我知道 StackTrace/reflection 很慢;兄弟,别喷我)

鉴于 ALL 属性声明相同,我希望能够做的是有一些简单/干净的方法来声明它们而无需复制相同的 get/set一遍又一遍的代码。
我需要所有属性的 Intellisense,这排除了使用例如。 ExpandoObject.

如果我在 C/C++ 领域,我可以使用宏,例如:

#define DEFPROP(name) \
public string name \
{ \
get { return _getValue(); } \
set { _setValue(value); } \
} \

然后:

public class Abc
{
DEFPROP(City)
DEFPROP(State)
...
}

但这当然是 C#。

那么……有什么好主意吗?

#### 编辑###
我想我原来的帖子不够清楚。
我的辅助函数 _getValue() 根据调用的属性执行一些自定义查找和处理。它不只是存储/检索简单的 prop 特定值。
如果我只需要简单的值,那么我会使用自动属性

public string { get; set; }

并完成它,不会问这个问题。

最佳答案

首先:CallerMemberNameAttribute确实注入(inject)调用成员名称,因此不需要反射:

public class Abc
{
public string City
{
get { return _getValue(); }
set { _setValue(value); }
}
public string State
{
get { return _getValue(); }
set { _setValue(value); }
}
private string _getValue([CallerMemberName] string memberName = "")
{
}

private void _setValue(string value,
[CallerMemberName] string memberName = "")
{
}
}

其次:类型成员的生成可以通过利用 T4 模板生成 .cs 文件来实现:

<#@ output extension=".cs" #>
<#
var properties = new[]
{
"City",
"State"
};
#>
using System.Runtime.CompilerServices;

namespace MyNamespace
{
public class Abc
{
<# foreach (var property in properties) { #>
public string <#= property #>
{
get { return _getValue(); }
set { _setValue(value); }
}
<# } #>
private string _getValue([CallerMemberName] string memberName = "") {}
private void _setValue(string value, [CallerMemberName] string memberName = "") {}
}
}

您甚至可以卸载 _setValue_getValue 以包含文件,从而也为其他模板提供可重用性。

T4 模板确实比宏有优势,代码可以随时重新生成。因此,即使在初始生成之后也可以应用对源代码的改编(可能是实现改编或属性重命名)。

关于c# - 有没有办法在 C# 中通过代码重用来实现多个属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30789690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com