Home > Back-end >  How to pass unknow model as parameter in Blazor
How to pass unknow model as parameter in Blazor

Time:02-19

On the method below, "Account" is a class (model). Is it possible to pass it as a parameter, such as GetDisplayName(object model, string col) so that the method can be called with different models?

 protected string GetDisplayName(string col)
        {
            var name = "";
            try
            {
                MemberInfo property = typeof(Account).GetProperty(col);
                var dd = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
                if (dd != null)
                {
                    name = Resources.ResourceManager.GetString(dd.Name);
                }
            }
            catch
            {
                name = "label not found";
            }
            return name;
        }

CodePudding user response:

You certainly could, just use model.GetType() instead of typeof(Account):

 protected string GetDisplayName(object model, string col)
 {
    var name = "";
    try
    {
        MemberInfo property = model.GetType().GetProperty(col);
        var dd = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
        if (dd != null)
        {
            name = Resources.ResourceManager.GetString(dd.Name);
        }
    }
    catch
    {
        name = "label not found";
    }
    return name;
}

However, I would advise against that, a cleaner way to implement this is to have all models that need to generate a display name implement an interface:

public interface IHasDisplayName
{
  string GetDisplayName();
}

CodePudding user response:

make it generic

protected string GetDisplayName<T>(string col) where T:class
        {
            var name = "";
            try
            {
                MemberInfo property = typeof(T).GetProperty(col);
                var dd = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
                if (dd != null)
                {
                    name = Resources.ResourceManager.GetString(dd.Name);
                }
            }
            catch
            {
                name = "label not found";
            }
            return name;
        }
  • Related