Home > Software design >  Accessing class fields throughout generic function (.Net Framework 4.8)
Accessing class fields throughout generic function (.Net Framework 4.8)

Time:12-31

First, I have this function that return true if the name is in the class:

public bool hasName<T>(List<T> Data, string name, Func<T, string> ClassName)
{
    foreach (T entry in Data)
    {
        if (ClassName(entry) == name)
        {
            return true;
        }
    }

    return false;
}

And it's called using:

hasName(Data, name, x => x.name)

The problem is, that i have another function that uses HasName but doesn't know about the field name.

public List<T> MergeClasses<T>(List<T> Pri, List<T> Sec, Func<T, string> ClassName)
{
    List<T> result = new List<T>();

    result.AddRange(Pri);

    foreach (T entry in Sec)
    {
        if (!new Functions().hasName(result, ClassName(entry), x => x.name))
        {
            result.Add(entry);
        }
    }

    return result;
}

How can i solve this?

CodePudding user response:

You would need an interface or base-class to use as a generic constraint; for example:

interface IHazHame {
    string Name {get;} // note property, not field
}

then your type with .name would need to implement that:

class Foo : IHazName {
    // ...
}

and you can restrict your generic method to T that satisfy this:

public List<T> MergeClasses<T>(List<T> Pri, List<T> Sec, Func<T, string> ClassName)
    where T : IHazHame
{
  // ... x => x.Name
}
  •  Tags:  
  • c#
  • Related