如何将字符串转换为类对象名称

时间:2016-05-14 09:42:48

标签: c# mongodb

我正在尝试从字符串中获取对象。我怎样才能做到这一点?程序应该在MongoDB中获取所选组合框的文本和搜索数据。

string parameter = cmbSearch.Text;
var results = collection.AsQueryable().Where(b => b.parameter.StartsWith(txtSearch.Text));

我想它应该是这样的。 b。参数替换为b.Author或b.Title ......

这是我的图书课程:

class Books
{
    [BsonId]
    public string ISBN { get; set; }
    [BsonIgnoreIfNull]
    public string Title { get; set; }
    [BsonIgnoreIfNull]
    public string Author { get; set; }
    [BsonIgnoreIfNull]
    public string Editor { get; set; }
    [BsonIgnoreIfNull]
    public string Year { get; set; }
    [BsonIgnoreIfNull]
    public int No { get; set; }
    [BsonIgnoreIfNull]
    public string Publisher { get; set; }
    [BsonIgnoreIfNull]
    public string PageSetup { get; set; }
    [BsonIgnoreIfNull]
    public string OriginalLanguage { get; set; }
    [BsonIgnoreIfNull]
    public string Translator { get; set; }
    [BsonIgnoreIfNull]
    public string OriginalName { get; set; }
    [BsonIgnoreIfNull]
    public int Count { get; set; }
}

2 个答案:

答案 0 :(得分:0)

我认为Activator.CreateInstance应该会有所帮助。

尝试使用它:

Type elementType = Type.GetType(cmbSearch.Text); //Be careful here if elementType is null. You must provide it like this: Type.GetType("MyProject.Domain.Model." + myClassName + ", AssemblyName");

dynamic dO = Activator.CreateInstance(elementType);

您可以在rextester上找到示例代码。

答案 1 :(得分:0)

您的问题可以通过反射 - .Net FW中包含的API来解决,您可以在运行时使用它来处理类的元数据。例如,获取所有属性的名称或获取/设置任何属性的值。 Read more about it from MSDN

使用有效值初始化组合框的示例代码:

var properties = typeof(Book).GetProperties();
List<String> comboboxValues = properties.Select(property => property.Name).ToList();

用户输入后:

String searchBy = "Author";
String searchValue = "Isaac Asimov";

List<Book> booksFromMongo = new List<Book>(); //TODO: Query mongo.

PropertyInfo searchByProperty = typeof(Book).GetProperty(searchBy);
List<Book> matches = booksFromMongo
    .Where(book => (String) searchByProperty.GetValue(book) == searchValue)
    .ToList();

显然你需要做更多的技巧来验证输入,处理不同类型的比较等,但这应该让你开始。

相关问题