【问题标题】:C# Class Library [closed]C# 类库 [关闭]
【发布时间】:2015-01-30 14:29:07
【问题描述】:

我想用 C# 开发一个类库,我会以分层方式调用其方法,如下所示:

using MyProduct.Common;

protected void Page_Load(object sender, EventArgs e)
{
    Utils myUtils = new Utils();

    int res = myUtils.Numbers.Add(1, 2);
    string text = myUtils.Text.ToUpper("test"); //***
}

是否可以使用命名空间、类、接口等等?

更新: 我有这样的库,但它不起作用,因为我不能“通过表达式引用类型”(上面有 *** 行)

namespace MyProduct.Common
{
    public class Utils
    {
        public static class Text
        {
            public static string ToUpper(string s)
            {
                return s.ToUpper();
            }
        }

    }
}

更新 2: 好吧,看来我需要澄清一下... 我有这个 MyProduct.Common.dll

namespace MyProduct.Common
{
    public static class Utils
    {
        public static class Text
        {
            public static void ToUpper(string s)
            {
                return s.ToUpper();
            }
        }

        public static class Number
        {
            public static void Add(int a, int b)
            {
                return (a + b);
            }
        }
    }
}

我有我的项目:

using MAD.Comum;
...
protected void Page_Load(object sender, EventArgs e)
{
   string x = Utils.Text.ToUpper("aa"); //this works
   string res = Utils.Number.Add(1, 2); //this works
}

现在有 2 个问题: - 是否可以在 2 个文件中将类 Number 和 Text 分开? - 这是一个好的设计吗?

【问题讨论】:

  • 是的,非常如此。您有具体问题吗?
  • 是的,当然可以,除非在 c# 中 imports MyProduct.Commonusing MyProduct.Common。你试过什么,有没有卡住?
  • 您需要记住 Utils 中的“状态”吗?如果没有,那么您可以将其设为静态类。
  • Utils 会有一般的东西,比如 myUtils.GenericFunction(),如果我想要一些特定的东西,比如数字或文本函数,我会调用 myUtils.Text.ToUpper() 或 myUtils.Numbers.Add() ... 那么,Utils 将在哪里以及如何站立?
  • 好的,我已经澄清了我的问题并且我有自己的答案......我该如何发布它?它仍然处于暂停状态..

标签: c# .net class class-library


【解决方案1】:

当然,你可以这样做:

namespace MyProduct.Common.Utils
{
    public static class Numbers
    {
        public static int Add(int n, int m)
        {
            return n + m;
        }
    }

    public static class Text
    {
        public static string ToUpper(string str)
        {
            return str.ToUpper();
        }
    }
}

你可以这样使用它:

MyProduct.Common.Utils.Numbers.Add(1, 2);

希望这会有所帮助。

干杯

【讨论】:

  • 谢谢@dario.pro,但是“Utils”呢?
  • 我已经编辑了我的答案。这是你想要的还是我错过了什么?
  • 也看到我的更新,我想使用一个变量,而不是 MyProduct.Common.Utils.Numbers.Add ... 不是可能吗?
  • 不,这不可能,伙计。我会接受我向您提出的建议,因为我认为这是一个很好的设计,并且可以满足您的需求。还是有其他原因让您这样做?
  • 我已经澄清了我的问题.. 谢谢。
猜你喜欢
  • 2010-09-23
  • 2010-09-05
  • 2013-10-26
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
  • 2010-10-02
  • 2010-09-08
相关资源
最近更新 更多