仅允许从 Class 继承的类型
Allow only types inherited from a Class
我有 class A 和 B(只是样本)
public class A
{
public long Id { get; set; }
public string Name { get; set; }
}
public class B : A
{
public B(long id,string name)
{
}
}
也想做
var b = new B(100, "myName");
Save(b);
我有一个保存方法,我只想允许从 A 继承的类型 Class 并且还使用了接受两个参数的构造函数
// I know this will work if my Class B has public B() {},
//but not sure how to restrict to have only the once which accept constructor with two parameters
private void Save<T>(T target) where T : A, new ()
{
//do something
}
C# 类型系统中没有任何内容可以强制执行该约束。您可以使用反射 API 在 运行时 .
进行验证
另一种选择是指定工厂:
interface IFactory<T> where T : A {
T Construct(object param1, object param2)
}
class BFactory : IFactory<B> {
public B Construct(object param1, object param2) {
return new B(param1, param2);
}
}
void Save<T>(T target, IFactory<T> tFactory) where T : A {
T newT = tFactory.Construct(a, b);
}
通用约束不支持带参数的构造函数。大多数情况下使用工厂或创建函数(例如 Is there a generic constructor with parameter constraint in C#? ),但由于对象是预先创建的并且您只想过滤允许哪些对象,因此更安全的方法是实现一个(空)接口并将其用作约束条件:
public class A
{
public long Id { get; set; }
public string Name { get; set; }
}
public class B : A, IAmB
{
public B(long id,string name)
{
}
}
public interface IAmB{}
这样约束将是:
private void Save<T>(T target) where T : A, IAmB
{
}
我有 class A 和 B(只是样本)
public class A
{
public long Id { get; set; }
public string Name { get; set; }
}
public class B : A
{
public B(long id,string name)
{
}
}
也想做
var b = new B(100, "myName");
Save(b);
我有一个保存方法,我只想允许从 A 继承的类型 Class 并且还使用了接受两个参数的构造函数
// I know this will work if my Class B has public B() {},
//but not sure how to restrict to have only the once which accept constructor with two parameters
private void Save<T>(T target) where T : A, new ()
{
//do something
}
C# 类型系统中没有任何内容可以强制执行该约束。您可以使用反射 API 在 运行时 .
进行验证另一种选择是指定工厂:
interface IFactory<T> where T : A {
T Construct(object param1, object param2)
}
class BFactory : IFactory<B> {
public B Construct(object param1, object param2) {
return new B(param1, param2);
}
}
void Save<T>(T target, IFactory<T> tFactory) where T : A {
T newT = tFactory.Construct(a, b);
}
通用约束不支持带参数的构造函数。大多数情况下使用工厂或创建函数(例如 Is there a generic constructor with parameter constraint in C#? ),但由于对象是预先创建的并且您只想过滤允许哪些对象,因此更安全的方法是实现一个(空)接口并将其用作约束条件:
public class A
{
public long Id { get; set; }
public string Name { get; set; }
}
public class B : A, IAmB
{
public B(long id,string name)
{
}
}
public interface IAmB{}
这样约束将是:
private void Save<T>(T target) where T : A, IAmB
{
}