只需添加另一层间接:
public void SomeMethod()
{
var listA = GetList("DataContext.ViewA");
var listB = GetList("DataContext.ViewB");
var listC = GetList("DataContext.ViewC");
}
public List<EntityObject> GetList(string dataContextName)
{
return (from x in GetSpecificSource(dataContextName)
where //Rest of where clause
select x).ToList();
}
public IEnumerable<MyType> GetSpecificSource(string dataContextName)
// Or: public IQueryable<MyType> GetSpecificSource(string dataContextName)
{
// ToDo: Return the correct source depending on the name. E.g.:
switch(dataContextName)
{
case "DataContext.ViewA":
return DataContext.ViewA;
case "DataContext.ViewB":
return DataContext.ViewB;
case "DataContext.ViewC":
return DataContext.ViewC;
}
}
更新如何使用反射
从具有所需名称的字段中检索值:
var fieldName = "ViewA";
var fieldFound = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if(fieldFound != null)
{
return fieldFound.GetValue(instance);
}
从具有所需名称的属性中检索值:
var propertyName = "ViewA";
var propertyFound = type.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if(propertyFound != null)
{
return propertyFound.GetValue(instance, null);
}
从具有所需名称的方法中检索值:
var methodName = "ViewA";
var methodFound = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if(methodFound != null)
&& methodFound.GetParameters().Length == 0)
{
return methodFound.Invoke(instance, null);
}
到目前为止,这些只是一些简单的例子。反思开辟了一个全新的问题和问题包。只需从上面的示例开始,检查它是否满足您的需求。否则,只需返回一个新问题。;-)