动态返回模型的值

时间:2018-11-01 08:52:10

标签: c# .net

我有一个方法,该方法调用API并返回一个模型,如下所示:

public class Book
{
   string Name { get; set; }
   string Author { get; set; }
   string Genre { get; set; }
}

这是一个示例函数

public static string GetValue(object reference)
{
    Book book = new Book();
    book.Name = "A";
    book.Author = "B";
    book.Genre = "C";

    return ?? // I have no idea
}

如果我调用GetValue(Name),则该方法应返回book.Name的值。如果我调用GetValue(Genre),则该方法应返回book.Genre

我该怎么办?

4 个答案:

答案 0 :(得分:2)

book.GetType().GetProperty(reference).GetValue(book, null);
  

确保reference是具有属性名称的字符串,例如:“名称”,“流派”

public static string GetValue(string propertyName)
{
    Book book = new Book();
    book.Name = "A";
    book.Author = "B";
    book.Genre = "C";

    return book.GetType().GetProperty(propertyName).GetValue(book, null).ToString();
    //Don't foget to handle exception

}

答案 1 :(得分:2)

虽然这似乎是一个奇怪的用例,但是您通常要返回书,然后直接访问书上的属性。如果您现在多次需要一个属性,则每次尝试使用此方法访问一个属性时,您的方法都会调用API。

所以直接方法可能是这样的:

   public static R GetValue<R>(Func<Book, R> selector) {
        Book book = new Book();
        book.Name = "A";
        book.Author = "B";
        book.Genre = "C";

        return selector(book);
    }

然后,您可以使用lambda函数来表示所需的内容,从而获得本书的价值:

var name = GetValue(b => b.Name);

然后,您可以将其推广为一个扩展方法,以便当您将其作为输入提供时可以返回任何值:

public static R GetValue<T, R>(this T value, Func<T, R> selector) {
    return selector(value);
}

然后创建一本新书,并获得如下值:

var name = book.GetValue(b => b.Name);

但是,您现在处在一个更直接的方法中:

var name = book.Name;

在这一点上,我们回到了我最初的建议,只要从获得书的位置获得整本书,然后直接访问书中的属性即可。

答案 2 :(得分:0)

我认为您可以通过将MemberExpression对象传递到方法中来实现功能,就像LINQ一样。因此,您可以使此方法通用,例如键入Book,然后将表达式作为第二个参数传递来选择属性值。

然后,您可以使用类似GetValue(myBook, book => book.Name)之类的方法。不幸的是,目前我无法显示给您,但是如果没有其他想法,我将在今天晚上计算机准备就绪时再次与您联系。

答案 3 :(得分:0)

如果我正确理解了您的问题,则可以按照以下步骤修改您的图书课程:

public class Book
{
    private string _name;
    private string _author;
    private string _genre;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public string Author
    {
        get { return _author; }
        set { _author = value; }
    }

    public string Genre
    {
        get { return _genre; }
        set { _genre = value; }
    }

    public string GetValue( Criteria criteria)
    {
        switch (criteria)
        {
            case Criteria.Author:
                return _name;                    
            case Criteria.Genre:
                return _genre;                    
            case Criteria.Name:
                return _name;
            default:
                return string.Empty;
        }
    }
}

public enum Criteria
{
    Name,
    Author,
    Genre
}