在使用obect的属性名强类型的方式属性、类型、方式、obect

2023-09-07 08:50:30 作者:时光乱了年华

有没有一种方法(在C#.NET 4.0),提供对象属性的名称在强类型的方式? 例如,如果我们有一个对象的人

Is there a way (in c# .Net 4.0) to provide object property name in strongly type manner? For instance, if we have an object Person

Public class Person{
    public string Name { get; set; }
    public int Age { get; set; }
    }

和我想发送给其他一些方法的参数名称,年龄属性名称,但不是作为字符串,但强类型:

And I want to sent to some other method the parameters Name, Age property name but not as string but strongly type:

SomeMethodThatWantToKnowKeys(Person.Name,Person.Age);

我想实现的是,如果有人更改属性的名称,他将不得不改变他们的属性名称,他被发送到SomeMethodThatWantToKnowKeys。 也许反射? 一个更好的办法将是不更新对象itsef或创建它的一个实例。

What I want to achieve is that if someone change the property name, he will have to change they property names he is sending to 'SomeMethodThatWantToKnowKeys'. Maybe reflection? A better way will be without updating the object itsef or creating an instance of it.

推荐答案

好了,同时也有一些丑陋的黑客有一个更好的和推行清洁解决方案。这个问题是因为抽象不到位。

Okay so while there are some ugly hacks there is a much better and clearner solution. This problem is because the abstraction is not in place.

什么是域名?一个字符串?这可能是一个int,双,焦炭,浮....什么......你真的不关心底层类型。你在乎一个名称的概念或概念。我知道这是更加深了一点,但是这方面的经验将帮助您不错的设计。

What is a name? A String? It could be an int, double, char, float....anything...you do not really care about the underlying type. You care about the concept or notion of a name. I know this is a bit more deep, but this experience will help you with good design.

下面是我的建议,现在,但我个人会去做得更多。

Here is what I suggest for now, but personally I might go do more.

public class PersonName
{
    public String Name { get; set; }
}

public class PersonAge
{
    public int Age {get;set;}
}

public class Person
{ 
    public PersonName PersonName {get;set;}
    public PersonAge PersonAge {get;set;}
}

所以,现在你的方法签名是:

So now your method signature is:

    SomeMethodThatWantToKnowKeys(PersonName,PersonAge);

类型安全是一个了不起的事情!

Type safety is an amazing thing!