正如Gilad Green 所说,您正在使用value 作为type。您可以执行以下操作:
class Program
{
static void Main(string[] args)
{
Employee employee = GetInstance<Employee>(Importance.Employee);
Teacher teacher = GetInstance<Teacher>(Importance.Teacher);
Console.WriteLine(employee.GetType());
Console.WriteLine(teacher.GetType());
Console.ReadKey();
}
public static T GetInstance<T>(Importance objType)
{
if (objType == Importance.Employee)
return (T)Convert.ChangeType((new Employee()), typeof(T));
else
return (T)Convert.ChangeType((new Teacher()), typeof(T));
}
}
public class Employee
{
string ID = "";
string Name = "";
}
public class Teacher
{
string ID = "";
string Name = "";
}
enum Importance
{
Employee,
Teacher
};
但是,正如我所见,如果您只想要给定类型的新对象,则不需要 Importance 枚举。您可以执行以下操作:
class Program
{
static void Main(string[] args)
{
Employee employee = GetInstance<Employee>();
Teacher teacher = GetInstance<Teacher>();
Console.WriteLine(employee.GetType());
Console.WriteLine(teacher.GetType());
Console.ReadKey();
}
public static T GetInstance<T>() where T : class, new()
{
return new T();
}
}
public class Employee
{
string ID = "";
string Name = "";
}
public class Teacher
{
string ID = "";
string Name = "";
}
我们可以再想一想,给出两个样本。一个是 Enum,一个是多态性。
如果你真的想保留Enum,那么我认为你的泛型类型带有 Enum 参数只是为了确保它不会返回不同的类型,所以它会是这样的:
class Program
{
static void Main(string[] args)
{
var employee = GetInstance<Employee>(Importance.Employee);
var teacher = GetInstance<Teacher>(Importance.Teacher);
Console.WriteLine(employee.GetType());
Console.WriteLine(teacher.GetType());
Console.ReadKey();
}
public static T GetInstance<T>(Importance importance) where T : Role, new()
{
if (typeof(T) == typeof(Employee) && importance != Importance.Employee)
{
throw new InvalidCastException();
}
if (typeof(T) == typeof(Teacher) && importance != Importance.Teacher)
{
throw new InvalidCastException();
}
return new T();
}
}
public abstract class Role { }
public class Employee : Role
{
string ID = "";
string Name = "";
}
public class Teacher : Role
{
string ID = "";
string Name = "";
}
public enum Importance
{
Teacher,
Employee
}
但我认为这没有意义。我会做类似的事情:
class Program
{
static void Main(string[] args)
{
var employee = GetInstance<Employee>();
var teacher = GetInstance<Teacher>();
Console.WriteLine(employee.GetType());
Console.WriteLine(teacher.GetType());
Console.ReadKey();
}
public static T GetInstance<T>() where T : Role, new()
{
var role = new T();
// do something important here
return role;
}
}
public abstract class Role { }
public class Employee : Role
{
string ID = "";
string Name = "";
}
public class Teacher : Role
{
string ID = "";
string Name = "";
}