How to create a typically limited property on an interface?

This is absolutely true:

public interface IWidgetGetter
{
    IEnumerable<T> GetWidgets<T>() where T : IWidget;
}

That is, it defines an untyped interface that includes a method for getting IEnumerablesome type that implements IWidget.

How to do this in a property?

Things that don't work:

IEnumerable<T> Widgets<T> { get; set; } where T : IWidget
IEnumerable<T> Widgets { get; set; } where T : IWidget
IEnumerable<T> Widgets where T : IWidget { get; set; }
IEnumerable<T> Widgets<T> where T : IWidget { get; set; }
+4
source share
2 answers

There is no such thing as a common property.

The type parameter is still a kind of parameter. Just as you cannot include a method that takes an argument into a property, you also cannot turn a general method into a property.

The closest you could do is the following:

public interface IWidgetGetter<T> where T : IWidget
{
    IEnumerable<T> Widgets { get; }
}
+10
source

@Lucas Trzesniewski , , TOutput, type T.

 public interface MyInterface<T> : IEnumerable<T>
        {    
            IEnumerable<TOutput> AsEnumerable<TOutput>();     
        }

TypeDescriptor.Converter, , , , , .

public class MyClass<T> : MyInterface<T>
{
    public IEnumerable<TOutput> AsEnumerable<TOutput>()
    {
       var converter = TypeDescriptor. GetConverter(typeof(T));
       //do what you want
       foreach(var item in someList)
       {
           var result = converter.ConvertTo(item, typeof(TOutput));
           yield return (TOutput)result:
       }
    }
}
+1

Source: https://habr.com/ru/post/1568032/


All Articles