1

I am refactoring my code and I want to replace these calls:

 OnClickEv onClickPr = GetScriptPr<OnClickEv>(controlProps); if (onClickPr != null && onClickPr.Value != null) _script.Add(onClickPr.Value.ToString()); OnDblClickEv onDblClickPr = GetScriptPr<OnDblClickEv>(controlProps); if (onDblClickPr != null && onDblClickPr.Value != null) _script.Add(onDblClickPr.Value.ToString()); OnKeyDownEv onKeyDownEv = GetScriptPr<OnKeyDownEv>(controlProps); if (onKeyDownEv != null && onKeyDownEv.Value != null) _script.Add(onKeyDownEv.Value.ToString()); 

with single function where I simply pass classes or Types that should be processed:

CreateSimplePropWithParam(controlProps, new List<Type>() { typeof(OnClivkEv), typeof(OnDblClickEv), typeof(OnKeyDownEv) }); 

Template function:

private T GetScriptPr<T>(List<ScriptPr> properties) where T : ScriptPr { var pr = properties.Where(x => x.GetType() == typeof(T)).FirstOrDefault(); return (T)pr; } 

But how to pass that Type parameter to Template?

private void CreateSimplePropWithParam(List<ScriptPr> controlProps, DesignerPlatform designerPlatform, object param, List<Type> propsList) { foreach (Type type in propsList) { T prop = (ScriptPr)GetScriptPr<T>(controlProps); <<< what to do with T? if (prop != null && prop.Value != null) {... }}} 
1
  • 1
    C# has no templates like in C++. C# has generics allowing strong-typing. Templates are the ancestors of generics. The usage of T comes from the word Template, so it is understandable that this causes confusion. Differences Between C++ Templates and C# Generics Commented Nov 5, 2019 at 8:21

1 Answer 1

2

To do this, you need to use reflection; in particular, you want MakeGenericMethod, i.e.

static readonly MethodInfo s_GetScriptPr = typeof(Whatever) .GetMethod("GetScriptPr", BindingFlags.Instance | BindingFlags.NonPublic); ... object result = s_GetScriptPr.MakeGenericMethod(type).Invoke(targetInstance, new object[] { controlProps }); 

Note: generics and reflection aren't easy to use together correctly, and if you can avoid it, you usually should.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for clarification. I will find a different way, using reflection looks reaaly complicated.
@Slappy it is complicated to just use it (like above)... to use it efficiently (in terms of speed and allocations) is much more complicated than that :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.