[英]Resolve property at runtime. C#
I have some class which have some code 我有一些班上有一些代码
public IEnumerable<TypeOne> TypeOne
{
get
{
if (db != null)
{
var col = db.Select<TypeOne>();
if (col.Count > 0) return col;
}
return db2.TypeOne;
}
}
public IEnumerable<TypeTwo> TypeTwo
{
get
{
if (db != null)
{
var col = db.Select<TypeTwo>();
if (col.Count > 0) return col;
}
return db2.TypeTwo;
}
}
So as You can see there is a lot of duplicated Code and there are same property name and item type of enumerable. 因此,您可以看到有很多重复的Code,并且有相同的属性名称和可枚举的项目类型。 I want to call some property of object like "obj.MyProp". 我想调用对象的某些属性,例如“ obj.MyProp”。 And MyProp must be resolved at runtime with some generic or non-generic method. 而且MyProp必须在运行时使用某种通用或非通用方法进行解析。 Is it possible? 可能吗?
Slightly incomplete answer but you'll get the general idea: 答案略有不完整,但您会得到大致的了解:
This is a scenario where you want generics. 在这种情况下,您需要泛型。
public IEnumerable<t> TypeSomething
{
get
{
if (db != null)
{
t col = db.Select<t>();
if (col.Count > 0) return col;
}
return GetDB<t>();
}
}
You'd need to implement GetDB() to return the appropriate db for any given type, but that'd be a single switch (or you can use reflection to find it) 您需要实现GetDB()来为任何给定类型返回适当的db,但这将是单个开关(或者您可以使用反射来找到它)
You can solve this by using generics: 您可以使用泛型来解决此问题:
public IEnumerable<TypeOne> TypeOne
{
get { return GetTable<TypeOne>(); }
}
public IEnumerable<TypeTwo> TypeTwo
{
get { return GetTable<TypeTwo>(); }
}
private IEnumerable<T> GetTable<T>()
{
if (db != null)
{
var col = db.Select<T>();
if (col.Count > 0) return col;
}
return db2.Select<T>();
}
There are a couple of ways to do this. 有两种方法可以做到这一点。 The best is probably a generic method: 最好的方法可能是通用方法:
public IEnumerable<T> dbSelect<T>() //may need type constraints here
{
return db != null
? db.Select<T>()
: null;
}
public IEnumerable<TypeOne> TypeOne
{
get { return dbSelect<TypeOne> ?? db2.TypeOne; }
}
public IEnumerable<TypeTwo> TypeTwo
{
get { return dbSelect<TypeTwo>() ?? db2.TypeTwo; }
}
If your db2
object has a generic Select<T>
-type method like db
does, it's even easier: 如果您的db2
对象像db
一样具有通用的Select<T>
-type方法,则更加简单:
public IEnumerable<T> dbSelect<T>()
{
return db != null
? db.Select<T>()
: db2.Select<T>(); //or db2.GetEntities<T>() or db2.OfType<T> or whatever
}
//Later, in your main code...
var x = dbSelect<TypeOne>();
var y = dbSelect<TypeTwo>();
This will be type safe, considerably faster than reflection, and will work with Intellisense. 这将是类型安全的,比反射快得多 ,并且将与智能感知工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.