基本概念是我希望得到一个属性'从签名方法中的输入返回。不是财产背后的数据。 EG:如果我选择“DEV' DEV'我想得到名为' DEV'的POCO Class属性。不是存储在POCO类的一部分中的数据。
最终目标是创建一个SQL部署脚本生成器,其中环境可能在每个环境中具有不同的命名数据库(相信我不是我的选择)。在示例中,在现实世界中简单并不像添加像QA'这样的字符串。或者' UAT'无论名字。有人根本没有遵循任何命名规则,只是随机命名,所以我发现并制作了一个集合,基本上会搜索和替换它。我正在制作一个包含不同名称的POCO对象。我意识到我可能需要规范化并改变对象,但我很好奇我是否可以在“'属性”中找到它。循环中的POCO类,而不是必须执行1,环境,名称,2,环境,名称等。
代码:
namespace SQL_Deployer
{
public class DatabaseListing
{
public string DatabaseName { get; set; }
public string Dev { get; set; }
public string DEMO { get; set; }
public string QA { get; set; }
public string UAT { get; set; }
public string PROD { get; set; }
}
public class DatabaseListings
{
protected static List<DatabaseListing> DataBaseListings { get; set; }
public DatabaseListings()
{
DataBaseListings = returnDatabaseListings();
}
private List<DatabaseListing> returnDatabaseListings()
{
return new List<DatabaseListing>{
new DatabaseListing{DatabaseName = "Main", Dev="Main", DEMO = "MainDemo", QA="MainQA", UAT="MainUAT", PROD="MainPROD"},
new DatabaseListing{DatabaseName = "Sub", Dev="Sub", DEMO = "SubDemo", QA="SubQA", UAT="SubUAT", PROD="SubPROD"}
};
}
}
}
namespace SQL_Deployer
{
public class SQL_Rewriter : DatabaseListings
{
private string _fileLocationSource;
private string _fileLocationTarget;
public string FileTextOriginal;
public string FileTextChanged;
public SQL_Rewriter(string aSourceFile, string aTargetFile)
{
_fileLocationSource = aSourceFile;
_fileLocationTarget = aTargetFile;
}
public void GetTextFromFile()
{
if (_fileLocationSource != null)
FileTextOriginal = File.ReadAllText(_fileLocationSource).ToUpper();
else
FileTextOriginal = "COULD NOT READ";
}
public void ChangeTextToNewFormat()
{
if (FileTextOriginal != null)
{
List<string> distinctEnvironments = new List<string> { "Dev", "DEMO", "QA", "UAT", "PROD" };
Dictionary<string, string> names = new Dictionary<string, string>();
distinctEnvironments.ForEach(x =>
names.Add(
x,
DataBaseListings.FirstOrDefault(y => y.DatabaseName == "Review").x // I want the 'property' extenstion of the object matching the 'distinctEnvironments' List I set above
)
);
// I should now have a dictionary for my environment with each enviroment 'property' I could loop through to find and replace text in a file.
foreach(var replace in names)
{
FileTextOriginal.Replace(replace.Key, replace.Value);
//TODO Write out file for each envionrment to sub directory in main placement.
}
}
else if (FileTextOriginal == "COULD NOT READ")
FileTextChanged = "COULD NOT READ INPUT";
else
FileTextChanged = "NO VALID INPUT TO READ";
}
}
}
答案 0 :(得分:1)
当然,使用反射:
var QAprop = typeof(DatabaseListing).GetProperty("QA");
或循环所有属性:
foreach(var prop in typeof(DatabaseListing).GetProperties())
string name = prop.Name;
从那里你可以得到属性的类型,属性等。
您必须再次使用反射 来获取值:
distinctEnvironments.ForEach(x =>
names.Add(
x,
typeof(DatabaseListing).GetProperty(x)
.GetValue(DataBaseListings.FirstOrDefault(y => y.DatabaseName == "Review"), null)
)