【发布时间】:2010-02-26 15:04:54
【问题描述】:
在我的业务层,我需要很多很多遵循模式的方法:
public BusinessClass PropertyName
{
get
{
if (this.m_LocallyCachedValue == null)
{
if (this.Record == null)
{
this.m_LocallyCachedValue = new BusinessClass(
this.Database, this.PropertyId);
}
else
{
this.m_LocallyCachedValue = new BusinessClass(
this.Database, this.Record.ForeignKeyName);
}
}
return this.m_LocallyCachedValue;
}
}
我仍在学习 C#,我正在尝试找出编写此模式的最佳方法,并向每个遵循此模式的业务层类添加方法,并替换正确的类型和变量名。
BusinessClass是必须替换的类型名,PropertyName、PropertyId、ForeignKeyName、m_LocallyCachedValue都是应该替换的变量。
这里可以使用属性吗?我需要反思吗?如何编写我在一个地方提供的骨架,然后只写一两行包含替换参数并让模式自行传播?
编辑:修改了我的误导性标题——我希望找到一个不涉及代码生成或复制/粘贴技术的解决方案,而是能够在某些基类中编写一次代码的骨架形式并将其“实例化”为许多子类作为各种属性的访问器。
编辑:这是我的解决方案,如建议的那样,但所选回答者未实施。
// I'll write many of these...
public BusinessClass PropertyName
{
get
{
return GetSingleRelation(ref this.m_LocallyCachedValue,
this.PropertyId, "ForeignKeyName");
}
}
// That all call this.
public TBusinessClass GetSingleRelation<TBusinessClass>(
ref TBusinessClass cachedField, int fieldId, string contextFieldName)
{
if (cachedField == null)
{
if (this.Record == null)
{
ConstructorInfo ci = typeof(TBusinessClass).GetConstructor(
new Type[] { this.Database.GetType(), typeof(int) });
cachedField = (TBusinessClass)ci.Invoke(
new object[] { this.Database, fieldId });
}
else
{
var obj = this.Record.GetType().GetProperty(objName).GetValue(
this.Record, null);
ConstructorInfo ci = typeof(TBusinessClass).GetConstructor(
new Type[] { this.Database.GetType(), obj.GetType()});
cachedField = (TBusinessClass)ci.Invoke(
new object[] { this.Database, obj });
}
}
return cachedField;
}
【问题讨论】:
标签: c# reflection templates attributes