Fully-qualified property name

后端 未结 1 504
别那么骄傲
别那么骄傲 2020-12-22 05:21

I\'m trying to prevent System.NullReferenceException.

I have a Company, which has a collection of Employees. Each Employee has a collection of Skills.

Select

相关标签:
1条回答
  • 2020-12-22 05:53

    I don't get it. Why not just:

    private void DeleteSelectedSkillFromSelectedEmployee()
    {
      if(Company != null &&
         Company.SelectedEmployee != null && 
         Company.SelectedEmployee.Skills != null)
      {           
        Company.SelectedEmployee.Skills.Remove(Company.SelectedEmployee.SelectedSkill);
        EmployeeSkillsListView.ScrollIntoView(Company.SelectedEmployee.Skills.Last());
      }
    }
    

    Or in C#6

    if(Company?.SelectedEmployee?.Skills != null) 
    {
      ...
    }
    

    If you still want to have that GetFullyQualifiedName method, the nearest you could use could be something like (doesn't check for errors and it's just a quick hack):

    public static string GetPathOfProperty<T>(Expression<Func<T>> property)
    {
      string resultingString = string.Empty;
      var  p = property.Body as MemberExpression;
      while (p != null)
      {             
        resultingString = p.Member.Name + (resultingString != string.Empty ? "." : "") + resultingString;
        p = p.Expression as MemberExpression;
      }
      return resultingString;           
    }
    

    Then use it like:

    GetPathOfProperty(() => Foo.Bar.Baz.SomeProperty );
    

    This would return a string containing "Foo.Bar.Baz.SomeProperty"

    Check it in a Fiddle

    0 讨论(0)
提交回复
热议问题