I have tried to use the example form Link to eliminate the code duplication.
if (Categories != null) {
foreach (var item in Categories)
{
if (item.ID != 0)
{
Category category = Category.Load(item.ID);
category.Name = item.Name;
category.Project = project;
category.Save();
}
else
{
if(!String.IsNullOrEmpty(item.Name))
{
Category category = new Category(project, item.Name);
category.Save();
}
}
}
}
if (Priorities != null)
{
foreach (var item in Priorities)
{
if (item.ID != 0)
{
Priority priority = Priority.Load(item.ID);
priority.Name = item.Name;
priority.Project = project;
priority.Save();
}
else
{
if (!String.IsNullOrEmpty(item.Name))
{
Priority priority = new Priority(project, item.Name);
priority.Save();
}
}
}
I am trying to do something as follows, but having the error message
Cannot invoke a non-delegate type
in the part
if (!String.IsNullOrEmpty(item.Name))
{
dynamic newObject = typeDynamic(project, item.Name);
newObject.Save();
}
SaveObjects(typeof(Category), Categories.ToList(), project);
SaveObjects(typeof(Priority), Priorities.ToList(), project);
Any help Please.
Thanks.
What is wrong and how can I correct that?
private void SaveObjects(Type type, dynamic currentItems, Project project)
{
dynamic typeDynamic = new StaticMembersDynamicWrapper(type);
foreach (var item in currentItems)
{
if (item.ID != 0)
{
dynamic classValues = typeDynamic.Load(item.ID);
classValues.Name = item.Name;
classValues.Project = project;
classValues.Save();
}
else
{
if (!String.IsNullOrEmpty(item.Name))
{
dynamic newObject = typeDynamic(project, item.Name);
newObject.Save();
}
}
}
}
You’ve defined typeDynamic to be a dynamic type but later try to use it as an actual Type (using it as a constructor
typeDynamic(...)). That’s not how they are intended to be used, just access to members using the dot (typeDynamic.someMember). Reading through the use of theStaticMembersDynamicWrapper, it doesn’t give you access to the constructors, only static members. You’d need to implementTryInvokein the StaticMembersDynamicWrapper class to use the type as a constructor. Add this to the class:Not terribly robust but should work enough for you. I would strongly recommend however a simpler approach as suggested by ck or my other non-dynamic approach.
A different (non-dynamic) approach you could take is to use delegates to your static functions. Refer to my answer in this question, Curious problem involving generics and static methods.