如何使用反射通过属性标签名称设置属性值?

6
我希望编写一个可重复使用的库,用于使用LDAP查询AD。我同时使用ActiveDs COM对象和System.DirectoryServices。
受Bart de Smet LINQ to AD的启发,我编写了SchemaAttribute和DirectoryAttributeAttribute类,并将它们与DirectorySource(Of T)类一起使用(是的,这是VBNET,但任何C#代码都可以帮助我,因为我精通这两种语言)。
现在,当使用LDAP(System.DirectoryServices)查询AD时,您可以选择要加载的属性/属性,通过DirectorySearcher类。然后,我编写了一个方法,该方法以ParramArray of String作为其参数,以便我在foreach()语句中将LDAP属性添加到DirectorySearcher.PropertiesToLoad()方法中。以下是一段代码,以使其更清晰(假设ldapProps参数始终包含值):
Public Function GetUsers(ByVal ParamArray ldapProps() As String) As IList(Of IUser)
    Dim users As IList(Of IUser) = New List(Of IUser)
    Dim user As IUser
    Dim de As DirectoryEntry = New DirectoryEntry(Environment.UserDomainName)
    Dim ds As DirectorySearcher = New DirectorySearcher(de, "(objectClass=user)")

    For Each p As String In ldapProps
        ds.PropertiesToLoad(p)
    Next

    Try
        Dim src As SearchResultCollection = ds.FindAll()
        For Each sr As SearchResult In src
            user = New User()
            // This is where I'm stuck... Depending on the ldapProps required, I will fill only these in my User object.
        Next
End Function

这是我的User类的一部分:

Friend NotInheritable Class User
    Implements IUser

    Private _accountName As String
    Private _firstName As String

    <DirectoryAttributeAttribute("SAMAccountName")> _
    Public Property AccountName As String
        Get
            Return _accountName
        End Get
        Set (ByVal value As String)
            If (String.Equals(_accountName, value)) Then Return

            _accountName = value
        End Set
    End Property

    <DirectoryAttributeAttribute("givenName")> _
    Public Property FirstName As String
        Get
            Return _firstName
        End Get
        Set (ByVal value As String)
            If (String.Equals(_firstName, value)) Then Return

            _firstName = value
        End Set
    End Property
End Class

现在,我想利用我放在 User 类属性顶部的那些属性。我知道如何获取这些属性,也知道如何获取我的属性。我不确定的是如何确保 SearchResult 类中的正确属性将被设置为正确的值,并传递到我的 User 类中。
编辑:由于时间紧迫,我无法等待熟悉 DirectorySource(Of T) 的概念,因为需要编写更多代码才能使其正常工作。作为一种解决方法,我正在编写一个 UserFactory 类,该类将通过我的 ActiveDirectoryFacade 调用。
编辑:这个 SO 问题似乎非常接近我想要实现的目标:Reflection, Attributes and Property Selection 编辑:这看起来就是我想要的:C# setting property values through reflection with attributes。是否有其他想法或可以确认这是正确的?
我还要提到的是,我被困在 .NET Framework 2.0 和 VBNET2005 中。否则,我会使用 Bart de Smet 的 LINQ to AD 库。
感谢任何帮助。
1个回答

3

我不熟悉DirectoryServices,但如果我理解你的问题正确,您可以使用反射来设置User对象的属性。为了设置正确的属性,您应该将属性的名称与用户对象的属性上保存的数据进行匹配。

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class DirectoryAttributeAttribute : Attribute
    {
        public DirectoryAttributeAttribute(string propertyName)
        {
            PropertyName = propertyName;
        }

        public string PropertyName
        {
            get; set;
        }
    }

    public class User
    {
        [DirectoryAttributeAttribute("SAMAccountName")]
        public string AccountName
        {
            get; set;
        }

        [DirectoryAttributeAttribute("givenName")]
        public string FirstName
        {
            get; set;
        }
    }

    // Finds property info by name.
    public static PropertyInfo FindProperty(this Type type, string propertyName)
    {
        foreach (PropertyInfo propertyInfo in type.GetProperties())
        {
            object[] attributes = propertyInfo.GetCustomAttributes(typeof(DirectoryAttributeAttribute, false));

            foreach (DirectoryAttributeAttribute attribute in attributes)
            {
                if (attribute.PropertyName == propertyName)
                {
                    return propertyInfo;
                }
            }
        }

        return null;
    }

    SearchResult searchResult = ...;

    if (searchResult != null)
    {
        User user = new User();

        Type userType = typeof (User);

        foreach (string propertyName in searchResult.Properties.PropertyNames)
        {
            // Find property using reflections.
            PropertyInfo propertyInfo = userType.FindProperty(propertyName);

            if (propertyInfo != null) // User object have property with DirectoryAttributeAttribute and matching name assigned.
            {
                // Set value using reflections.
                propertyInfo.SetValue(user, searchResult.Properties[propertyName]);
            }
        }
    }

如果你要填充的属性名称可能会改变,你可以将属性的映射存储在字典中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接