[英]Loop through all objects in a class at compile time C#
我需要在編譯時將我的類中的所有屬性連接起來構建一個字符串。 我見過類似的問題,但他們都在處理運行時場景。 基本上,我有一千個屬性,寧願不再手工列出它們。 我知道使用反射來使用typeof(X).getProperties(...),但是在運行時使用反射我不會有任何性能損失。 有沒有辦法讓我遍歷我的類中的所有屬性來創建我所有屬性的字符串?
Class1 : SomeInterface
{
int1;
int2;
...
int1000;
string stringOfAllProperties;
public getAllPropertiesAsString()
{
return stringOfAllProperties = int1+int2+int3...;
}
}
我認為只有反思會幫助你。 你可以做的是引入字典,其中鍵將是類型,值將是字符串連接結果。 該詞典將在您的應用程序中用作單例。 因此,您將僅為每種類型計算一次字符串,從而幾乎完全消除性能損失。
正如其他人所提到的,如果你有一千個屬性,你可能會遇到設計問題。 解決這個設計問題將是我的第一選擇,但如果這不是一個選擇......
Visual Studio通過T4模板支持編譯時(或准確地說:保存時)代碼生成,即,您可以執行以下操作:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
class MyClass
{
<# var properties = new string [] {"int1", "int2", "int3", ...}; #>
<# foreach (string property in properties) { #>
private int <#= propertyName #>;
<# } #>
public string getAllPropertiesAsString()
{
return ""
<# foreach (string property in properties) { #>
+ <#= propertyName #>;
<# } #>
}
}
請注意,您必須在Visual Studio 2017安裝過程中安裝“Visual Studio擴展開發”工作負載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.