I have the following classes
public interface IHtmlString
{
string ToHtmlString();
}
public class BaseClass<T> where T : BaseClass<T>, IHtmlString
{
public BaseClass()
{
}
public T Method1()
{
return (T)this;
}
public T Method2(string key, object value)
{
return (T)this;
}
public string ToHtmlString()
{
return ToString();
}
}
public class DerivedClassA : BaseClass<DerivedClassA>
{
public DerivedClassA MethodSpecificToClassA()
{
return this;
}
public override string ToString()
{
return "<div/>";
}
}
public class DerivedClassB : BaseClass<DerivedClassB>
{
public DerivedClassB MethodSpecificToClassB()
{
return this;
}
public override string ToString()
{
return "<span/>";
}
}
Note that the method returns this
instance so that i can chain methods, like below
var a = new DerivedClassA()
.Method1()
.MethodSpecificToClassA()
.ToHtmlString();
However im getting compile time error
Severity Code Description Project File Line Suppression State Error CS0311 The type 'DerivedClassA' cannot be used as type parameter 'T' in the generic type or method 'BaseClass'. There is no implicit reference conversion from 'DerivedClassA' to 'System.Web.IHtmlString'. WebApplication5 C:\\MyProjects\\WebApplication5\\WebApplication5\\Models\\BaseBuilder.cs 27 Active
How do i refactor these classes so i have IHtmlString
interface on base class only?
this worked
public class BaseClass<T> : IHtmlString where T : BaseClass<T>
{
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.