我不知道如何适当地扩展类

时间:2022-08-22 21:17:52

I'm using some pre-built code in asp.net. It provides me with a MembershipUser class and also has several other classes that use MembershipUser.

我在asp.net中使用一些预先构建的代码。它为我提供了一个MembershipUser类,并且还有其他几个使用MembershipUser的类。

I want to add a new property to MembershipUser without changing anything else. I still want all the pre-made functions to work with it.

我想向MembershipUser添加一个新属性,而不需要更改任何其他内容。我仍然希望所有的预制函数都能用它。

How can I extend MembershipUser to include a new property without creating a separate class that the other functions have no knowledge of?

如何扩展MembershipUser来包含一个新属性,而不创建其他函数不知道的单独类?

2 个解决方案

#1


2  

in C# you only have three options for extending classes:

在c#中,扩展类只有三个选项:

  1. Inheretance
  2. Inheretance
  3. Decoration (MSDN Link)
  4. 装饰(MSDN链接)
  5. Extension Methods
  6. 扩展方法

Sadly, none of them will do what you are trying to achieve.

遗憾的是,他们中没有人会做你想做的事情。

#2


1  

If you can inherit from the class, do that. For example if your property is a string

如果可以从类继承,就这样做。例如,如果您的属性是字符串

public class ExtendedMembershipUser : MembershipUser
{
    public string MyNewProperty { get; set; }
}

Or add an extension method if you can't inherit (you can't add a property):

如果不能继承(不能添加属性),也可以添加扩展方法:

public static class MembershipUserExtensions
{
    public static string MyNewMethod(this MembershipUser user)
    {
        return "answer";
    }
}

#1


2  

in C# you only have three options for extending classes:

在c#中,扩展类只有三个选项:

  1. Inheretance
  2. Inheretance
  3. Decoration (MSDN Link)
  4. 装饰(MSDN链接)
  5. Extension Methods
  6. 扩展方法

Sadly, none of them will do what you are trying to achieve.

遗憾的是,他们中没有人会做你想做的事情。

#2


1  

If you can inherit from the class, do that. For example if your property is a string

如果可以从类继承,就这样做。例如,如果您的属性是字符串

public class ExtendedMembershipUser : MembershipUser
{
    public string MyNewProperty { get; set; }
}

Or add an extension method if you can't inherit (you can't add a property):

如果不能继承(不能添加属性),也可以添加扩展方法:

public static class MembershipUserExtensions
{
    public static string MyNewMethod(this MembershipUser user)
    {
        return "answer";
    }
}