Get a list of common types that apply to any class.

I have a special need that I cannot understand. I did some research on this, but cannot find an acceptable solution.

I have a base class:

public abstract class BaseProvider<T> {}

this class, in turn, is inherited by two different provider classes:

public sealed class MonkeyProvider<T> 
       : BaseProvider<MonkeyProvider<T>> 
         where T 
       : IAnimalProvider

Inside the IAnimalProvider interface, I set one property that all implementations should output. Now MonkeyProvider, and possibly DonkeyProvider or something similar, should know what the assigned value for the property is for the root instance:

public class JoburgZoo
       : IAnimalProvider
{
     #region IAnimalProvider members
     public string Id{ get; set; }
     #endregion
}

// somewhere in a console application
public static void Main(string[] args)
{
     JoburgZoo zoo = new JoburgZoo();
     zoo.Id = "Mammals";

     **// edit: an instance of the provider will be created**
     MonkeyProvider<JoburgZoo> mp = new MonkeyProvider<JoburgZoo>();
     mp.CheckMonkeys(zoo); // where CheckMonkeys(JoburgZoo) is a method in the provider
}

Now, here is my question:

BaseProvider, , . "Id" , , , (, , ).

:

Type type = typeof(T); // this returns BaseProvider<MonkeyProvider<T>>
var generic = type.GetGenericTypeDefinition(); // brings back BaseProvider<T>

T, , . , BaseProvider.

.

//. . MonkeyProvider<T> JoburgZoo, ProviderBase<T> :

ProviderBase<MonkeyProvider<JoburgZoo>>

, JoburgZoo , BaseProvider<T> MonkeyProvider<T>.

, .

+3
1

,

    class BaseProvider<T>
    {
        //...
    }

System.Int32:

        Type type = typeof(BaseProvider<Int32>);
        foreach (var arg in type.GetGenericArguments())
        {
            MessageBox.Show(arg.FullName);
        }
+2

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


All Articles