0
public class Table<T> where T:SomeClassWithIntegerID
{
    private Dictionary<int, T> map = new Dictionary<int, T>();

    public bool isInMemory(int id)
    {
        if (map.ContainsKey(id))
            return true;
        return false;
    }

    public T setIt(T obj)
    {
        map[obj.id] = obj;
    }

    public T getIt(int id)
    {
        return map[id];
    }
}

例子:

private static Table<User> table = new Table<User>;

class User : SomeClassWithIntegerID
{
    public string name { get; set; }
    public string password { get; set; }
}

class SomeClassWithIntegerID
{
    public int id { get; set; }
}

我现在可以检查是否Table持有具有特定 ID 的用户,因为我使用它作为密钥,但现在我无法检查是否Table持有Bob 或其他什么Username我希望能够做类似的事情,table.isInMemory(name, "bob")但是泛型类型怎么可能呢?

我需要创建一个函数,允许最终用户指定该字段的字段和预期值,之后 Table 将遍历该类的所有对象,存储在 Dictionary 中,以查看是否有与该值匹配的字段.

这可能吗?

4

2 回答 2

3
public bool IsInMemory(Func<T, bool> predicate)
{
    return map.Values.Any(predicate);
}

然后,您可以将其称为:

table.IsInMemory(u => u.Name == "bob");

如果你想使用一个属性名称和值来匹配你可以添加一个重载:

public bool IsInMemory(string propertyName, object value)
{
    PropertyInfo property = typeof(T).GetProperty(propertyName);
    if(property == null) throw new ArgumentException("Invalid property name: " + propertyName);

    var predicate = new Func<T, bool>(item => object.Equals(value, property.GetValue(item, null)));
    return IsInMemory(predicate);
}
于 2012-10-03T17:22:21.207 回答
2

我会用 Where-method 来补充 Lee 的回答,以便使用 LINQ 进行查询:

public IEnumerable<T> Where(Func<T, bool> predicate)
{
    return map.Values.Where(predicate);
}

And an example:

table.Where(x => x.name.Contains("natli"))
     .OrderBy(x => x.name);

To answer your actual question, you can (if you're using .NET 4.0) use the dynamic type, which resolves all methods and such at runtime, to call methods or properties that the compiler doesn't know about from its context.

dynamic dynObject = someObject;
dynObject.SomeMethod("Hi there", 27); // Call whatever method or property you "know" exist
于 2012-10-03T17:34:48.823 回答