Storing the generic class T in a variable and reusing it in sub methode.
For a WebService with crud on few object:
Foo: Bar: Etc..
SetFoo SetBar SetEtc
GetFoo GetBar GetEtc
UpdateFoo UpdateBar UpdateEtc
DeleteFoo DeleteBar DeleteEtc
GetList .. ..
GetPending .. ..
Processed .. ..
I have the following singleton generic wrapper on client side, with methode like:
public bool Get<T>(int i, out DloExtention result)
// DloExtention is an interface implemented by foo, bar, etc..
{
result = null;
try
{
if (typeof(T) == typeof(Foo))
{
result = WebserviceClient.GetFoo(i);
}
else if (typeof(T) == typeof(Bar))
{
result = WebserviceClient.GetBar(i);
}
else if (typeof(T) == typeof(Etc))
{
result = WebserviceClient.GetEtc(i);
}
else
{
throw new NotSupportedException("Get<T>, T is not a supported type.");
}
}
catch (Exception ex)
{
Log4N.Logger.Error($"Error in Namespace.ClientSide.Get<{nameof(T)}>(int {i} ). " + ex.Message);
return false;
}
return true;
}
So I can handle all the type simply with the same generic object:
class Processor
{
HashSet<int> validOperation = new HashSet<int>();
HashSet<int> invalidOperation = new HashSet<int>();
internal void Run<T>()
{
if (Wrapper.Instance.GetListPending<T>(out int[] newEntityList) && newEntityList.Any())
{
ProcessEntities<T>(newEntityList, false);
}
}
private void ProcessEntities<T>(int[] idsEnt, bool singleMode)
{
foreach (var idEnt in idsEnt)
{
ProcessEntity<T>(idEnt, false);
}
CloseValidOperation();
RemoveInvalidOperation();
}
internal void ProcessIncident<T>(int idEnt)
{
if (Wrapper.Instance.Get<T>(idEnt, out LanDataExchangeCore.LanDataExchangeWCF.DloExtention currentEntity))
{
if (currentEntity.isValid() && currentEntity.toLocalDB())
{
validOperation.Add(idEnt);
}
else
{
invalidOperation.Add(idEnt);
}
}
}
Only Wrapper.Instance.Get<T>
and Wrapper.Instance.GetListPending<T>
needs the generic parameter.
But every methode in the way need to use it only to be able to deliver <T>
to the last methode.
Is there a way to save the <T>
in the Run<T>
call into a private variable so inner methode of the class can use it ?
I have try adding a Type myType;
but can't find the way to use it in generic call. Exemple for the Wrapper.Instance.Get<T>
Type myType; // class property
var fooWrapperGet = typeof(Wrapper).GetMethod("Get");
var fooOfMyTypeMethod = fooWrapperGet.MakeGenericMethod(new[] { myType });
//fooOfMyTypeMethod.Invoke(Wrapper.Instance , new object[] { new myType() });
// fooWrapperGet, as my wrapper is a singleton, Wrapper dont exposed Get<T>, but Wrapper.instance will expose it.
// new myType() <- do not compile.