c# - How to cast a Generic<T> to a Generic<R> where T is a subclass of R? -
is there way define explicit converter or similar such compiler can automatically populate generic<t>
generic<r>
where t : r
?
the error message is:
the value "reference
1[dog]" not of type "reference
1[pet]" , cannot used in generic collection.
my reference class looks this:
public interface ireference<t> { t value { get; } } public class reference<t> : ireference<t> { #region properties public string ref_type { get; set; } public string ref_id { get; set; } public uri href { get; set; } private bool resolved = false; private t _value = default(t); public t value { { if( !resolved && href != null ) resolve(); else if( href == null ) return null; return _value; } } #endregion #region constructors public reference() { } public reference(string ref_id) { this.ref_id = ref_id; } #endregion #region members private void resolve() { if( href != null ) { _value = apirequestmethods.geturi<t>(href); resolved = true; } else throw new exception("cannot resolve reference because href property has not been set."); } #endregion }
this work if generic type interface, , make generic type covariant, ie: igeneric<out t>
.
note work interfaces or delegates. details, see covariance , contravariance in generics.
Comments
Post a Comment