如何在传递对象作为参数时解析自定义类型
本文关键字:参数 类型 自定义 对象 | 更新日期: 2023-09-27 18:09:20
我想从任何程序调用Create
方法来匹配基于while执行操作传递的类类型。
所以问题是我如何解决一个匿名类型,而传递给私有方法?
我从:
_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
}
}
如何将您的类更改为:
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");
}
}
这看起来像是一个不太理想的泛型用例。你考虑过使用简单的方法重载吗?试试以下命令:
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 {}
下面是上面的dotnetfiddle: https://dotnetfiddle.net/lzaAba