Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Its not possible to create such an restriction. You should check the input at runtime and throw a helpful exception error message.</p> <p>You can however do something like:</p> <pre><code>public interface IWellKnown { int PropertyA { get; } int PropertyB { get; } } public abstract class WellKnownBase&lt;T&gt; : IWellKnown { IWellKnown.PropertyA { get { return Convert(this.PropertyA); } } IWellKnown.PropertyB { get { return Convert(this.PropertyB); } } public T PropertyA { get; } public T PropertyA { get; } protected virtual int Convert(T input) { return (int)input; } } </code></pre> <p>Using such a base class guides the one implementing a concrete version to provide a way to cast to <code>int</code>. The explicit interface implementation provides access to <code>int</code> typed accessors while the "real" class still provides the original type.</p> <pre><code>public class WellKnownFloat : WellKnownBase&lt;Float&gt; {} </code></pre> <p>Would provide you with a class for float. If the type is not castable to int you can provide a custom converter:</p> <pre><code>public class WellKnownTimeSpan : WellKnownBase&lt;TimeSpan&gt; { protected override int Convert(TimeSpan input) { return (int)input.TotalMilliseconds; } } </code></pre> <p>By the way, using linq and adding the requirement to the interface you can rewrite your function to <code>input.Select(x =&gt; x.PropertyA + x.PropertyB)).ToArray()</code>.</p> <p>PS: please check the code using VisualStudio, I am just writing it out of my head without compiler support ;) There may be small compiletime errors.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload