[英]Calling a class method dynamically
编辑:在现实生活中,我没有Book Class。 这只是一个清楚的例子。 真正的问题确实需要反思才能解决。
假设我有一些课程:
书,苹果,门。
class Book
{
...
public decimal getPrice()
{...}
public string getTitle()
{...}
public decimal getAuthor()
{...}
}
和其他班级一样。
我可以从字符串动态调用类方法吗?
Book myBook = new Book("Title", "Author", 44);
string title = runMethod(myBook, "getTitle");
您可以通过Reflection做到这一点。
Book myBook = new Book("Title", "Author", 44);
string title = (string) myBook.GetType().GetMethod("getTitle").Invoke(myBook, null);
您可以使用反射来使用类似这样的东西:
class Program
{
static void Main(string[] args)
{
var b = new Book("Book Title", 2342);
Console.WriteLine(CallMethod(b, "GetTitle", "Not Found"));
}
public static K CallMethod<T,K>(T a, string method, K defaultOjb)
{
var t = a.GetType();
var mi = t.GetMethod(method);
if (mi == null) return defaultOjb;
var ret=mi.Invoke(a, new object[] {});
return (K) ret;
}
}
public class Book
{
private readonly string _title;
private readonly decimal _price;
public decimal GetPrice()
{
return _price;
}
public string GetTitle()
{
return _title;
}
public Book(string title, decimal price)
{
_title = title;
_price = price;
}
}
查找反射和MethodInfo。 我相信这将引导您走上所要寻找的道路。
先前的答案在提及反思时是正确的。
但是,除非您的真实问题与您的示例有很大不同,否则没有必要。
从您的示例来看,您可以直接直接调用它:
string title = mybook.getTitle();
如果要点是您不知道并且不想关心要获得的特定对象,则可以使用基类,也可以使用接口。
public interface IProduct
{
string Name { get; }
string Type { get; }
float Price { get; }
}
使您的类实现IProduct,并确保您的类将实现所需的属性或函数,并且无论您使用的是“ Book”,“ Apple”还是“ Door”,它们都将是公共的”。
public void OutputProductsToConsole(List<IProduct> products)
{
for (int i = 0; i < products.Count; i++)
{
Console.WriteLine(products[i].Name + ": " + products[i].Price);
}
}
反射是可能的,但是在示例中,直接调用该方法会更简单:
string title = myBook.getTitle();
您正在使用属性值实例化新的Book类。 您是否未分配值,以便以后可以将其取回?
public class Book
{
private string _title;
private decimal _price;
private string _author;
public Book(string title, decimal price, string author);
{
_title = title;
_price = price;
_author = author;
}
public string Title
{
get
{
return _title;
}
}
public decimal Price
{
get
{
return _price;
}
}
public string Author
{
get
{
return _author;
}
}
}
更好的是,如果这些方法对于您所有的类都是通用的,则创建一个接口并在您的类中继承该接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.