我想从任何程序中调用Create方法,以匹配在执行过程操作的基础上传递的类类型。
因此,问题是如何在传递给私有方法时解决匿名类型?
我打电话是从:
_productService.Create<Supplier>(_supplier);我的课堂教学方法:
public class ProductService
{
public void Create<T>(T obj)
{
switch (obj.GetType().Name)
{
case "Supplier":
Supplier(); //Call Supplier Method;
break;
case "Product":
Product(); //Call Supplier Method;
break;
default:
break;
}
}
private void Supplier<T>(T s)
{
//statements
}
private void Product()
{
//statements
}
}发布于 2015-08-22 15:54:49
把你的班级改为:
public class ProductService
{
public void Create<T>(T obj)
{
if (typeof(Supplier) == typeof(T))
Supplier(obj); //Call Supplier Method;
else if (typeof(Product) == typeof(Product))
Product(); //Call Product Method;
else
throw new ArgumentOutOfRangeException("Unrecognized type", "type");
}
private void Supplier<T>(T s)
{
//statements
Console.WriteLine("Supplier");
}
private void Product()
{
//statements
Console.WriteLine("Product");
}
}发布于 2015-08-22 16:10:46
对于泛型来说,这看起来不是一个理想的用例。您是否考虑过使用简单的方法重载。尝试以下几点:
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var service = new ProductService();
service.Create(new Product());
service.Create(new Supplier());
service.Create(new {name="test"});
}
}
public class ProductService
{
public void Create(Product obj)
{
Product();
}
public void Create(Supplier obj)
{
Supplier();
}
public void Create(Object obj)
{
Console.WriteLine("Unknown type called" + obj.GetType().Name);
}
private void Supplier()
{
Console.WriteLine("Supplier called");
}
private void Product()
{
Console.WriteLine("Product called");
}
}
public class Product {}
public class Supplier {}下面是上面所述的点小提琴:https://dotnetfiddle.net/lzaAba
https://stackoverflow.com/questions/32157883
复制相似问题