我是 C# 的新手,很抱歉,如果有人已经问过这个问题,我没有找到任何答案。
标题中的问题很清楚,所以这是我要实现的代码:
/// <typeparam name="M">Entity model</typeparam>
public class FormBuilder<M>
{
/// <typeparam name="F">Implementation of FieldType</typeparam>
public FormBuilder<M> Add<F>(string propertyName, F options) where F : FieldType<?>
{
// ...
return this;
}
}
/// <typeparam name="T">Type of the field</typeparam>
public abstract class FieldType<T>
{
public T Data { get; set; }
public bool Disabled { get; set; } = false;
public bool Required { get; set; } = true;
public string Hint { get; set; }
public IDictionary<string, string> Attributes { get; set; }
}
public class TextType : FieldType<string>
{
public bool Trim { get; set; } = true;
public string Placeholder { get; set; }
}
最佳答案
由于 C# 的泛型是具体化,而 Java 使用类型删除 来实现其泛型,因此在某些边缘情况下会出现一些根本差异,例如这种情况。长话短说:您需要为 FieldType<>
指定一个实际的通用类型.好消息是您可以通过泛型来做到这一点。
public FormBuilder<M> Add<F, T>(string propertyName, F options) where F : FieldType<T>
{
// ...
return this;
}
当然,您需要考虑是否真的需要 F
通用类型。根据您正在做的事情,您可能可以通过更直接的方式逃脱惩罚:
public FormBuilder<M> Add<T>(string propertyName, FieldType<T> options)
{
// ...
return this;
}
关于C# 相当于 Java `<F extends FieldType<?>> void add(F field)`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57742895/