编程语言
首页 > 编程语言> > c#-根据其他属性设置属性的方法

c#-根据其他属性设置属性的方法

作者:互联网

所以,我有这段代码

        Process[] processesManager = Process.GetProcesses();
        List<ProcessInfo> temporaryProcessesList = new List<ProcessInfo>();
        for (int i = 0; i < processesManager.Length; ++i)
        {
            temporaryProcessesList.Add(new ProcessInfo(processesManager[i].ProcessName, processesManager[i].Id, TimeSpan.Zero, "Group"));
        }

        processesList = temporaryProcessesList.GroupBy(d => new {d.Name}).Select(d => d.First()).ToList();

此代码用于获取当前进程.然后,我将这些过程添加到temporaryProcessesList.我想根据进程的名称来设置属性,而不是简单的字符串“ Group”.例如,如果进程的名称为Leagueoflegends.exe,那么我想将组设置为“游戏”,如果进程的名字为devenv.exe,则我要将组设置为“软件开发”.

我的问题是,如何以最简单/最好的方式做到这一点?我正在考虑将Dictionary与string和enum一起使用.并将ProcessName与字符串进行比较.但是也许有更好的方法可以做到这一点.

ProcessInfo是具有4个属性和构造函数的简单类.

public class ProcessInfo
{
    private string Name { get; set; }
    private int Id { get; set; }
    private TimeSpan Time { get; set; }
    private string Group { get; set; }

    public ProcessInfo(string name, int id, TimeSpan time, string group)
    {
        Name = name;
        Id = id;
        Time = time;
        Group = group;
    }
}

解决方法:

也许这就是您想要的:

public class ProcessInfo
{
    private string _name;
    private string Name
    { 
      get { return _name; }
      set
      {
          _name = value;
          UpdateGroupName();
      }
    }
    private int Id { get; set; }
    private TimeSpan Time { get; set; }
    private string Group { get; set; }

    private void UpdateGroupName()
    {
        Group = ProcessNames::GetGroupFromProcessName(Name);
    }

    public ProcessInfo(string name, int id, TimeSpan time)
    {
        Name = name;
        Id = id;
        Time = time;
    }
}

internal static class ProcessNames
{
    private static Dictionary<string, string> _names;

    public static string GetGroupNameFromProcessName(string name)
    {
        // Make sure to add locking if there is a possibility of using
        // this from multiple threads.
        if(_names == null)
        {
            // Load dictionary from JSON file
        }

        // Return the value from the Dictionary here, if it exists.
    }
}

这种设计不是完美的,但希望您能明白.您也可以将Group名称的更新移至构造函数,但如果在构造后设置属性,则不会更改Group名称.

另外,您可以使用INotifyPropertyChanged和/或依赖项注入来清理接口. https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx

标签:c-4-0,c-3-0,c-2-0,c,net
来源: https://codeday.me/bug/20191026/1939942.html