开发者

Creating a function that will handle objects with common properties

Take开发者_如何学C this as an example

I have trimmed this example for readability and you may not find the use of this concept here.

class Teacher()
{
 public Name {get; set;}
 public Salt {get; set;}
 public Department{get; set;}
}

class Student()
{
 public Name {get; set;}
        public Salt {get; set;}
 public Section{get; set;}
}

public string GetEncryptedName(object Person)
{
 //return encrypted name based on Name and Salt property
 return encrypt(object.Salt,object.Name)
}

callig the function

GetEncryptedName(Teacher)
GetEncryptedName(Student)

How do you implement this kind of stuff?


You need to implement a common interface / base class in both Teacher and Student:

interface IPerson {
    string Name {get;set;}
    string Salt {get;set;}
}

class Teacher : IPerson...

class Student : IPerson...

public string GetEncryptedName(IPerson person)
{
 //return encrypted name based on Name and Salt property
 return encrypt(person.Salt,person.Name)
}

That way you can call GetEncryptedName when any object that implements the IPerson interface and is guaranteed to implement the Name and Salt properties


Here is one approach. Have both Teacher and Student inherit from a base class, let's call it Person. This Person class will have two properties, Name and Salt, and it can also have a public method called GetEncryptedName(), which will keep your implementation organized in a single place.


You need an Interface that both classes implement. Then you can pass the GetEncryptedName() method an interface.

interface IPerson
{
 string Name {get; set;}
 string Salt {get; set;}
 string Section {get; set;}
}

class Teacher : IPerson
{
 public Name {get; set;}
 public Salt {get; set;}
 public Section{get; set;}
 public Department{get; set;}
}

class Student : IPerson
{
 public Name {get; set;}
 public Salt {get; set;}
 public Section{get; set;}
}

public string GetEncryptedName(IPerson person)
{
 //return encrypted name based on Name and Salt property
 return encrypt(person.Salt,person.Name)
}

Here is the MSDN reference to interfaces: interface (C# Reference)


you could define an interface that both the Teacher and Student clases implement. Something like: That is what I would do.

interface IEncryptionInfoProvider
{
    Name {get; set;}
    Salt {get; set;}
}

If you do not wish to define this interface, you would have to use reflection to get the values of the properties by name. There are plenty of examples, info on the web on this topic. http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜