Class Library in C#

吃可爱长大的小学妹 提交于 2019-12-25 09:44:16

问题


I tried to create a class library that is being used in a winforms application in C#.

In my application I have input from a textbox and through a button click I'm instantiating my event with one parameter (from the textbox). I tried to create a constructor with this one parameter - but to no avail. It seems if I just add a class to be existing project I can do this but not when referencing a class library.

Just wanted to find a way to use a one parameter constructor within a class library if possible. Please help. (this may not work logically because when I reference the class library - I am actually going outside the original assembly - but maybe....)


回答1:


If your new class library is in a separate C# project you need to set a reference to that project from your WinForms app before you can use the class.

Of course I'm trying to read between the lines of your original post. It sounds like you know how to make it work, just not when the class is defined in a seperate project. If I've misunderstood, please give more info.




回答2:


Not enough site experience to upvote or comment myself yet, but DRapp's answer fixed my problem. Since the original question is a bit vague I thought I'd detail what I was seeing a bit more:

I am writing a metro application in C++ which references a class library created in C#. Creating objects exported from the C# module was working fine, unless their constructors had parameters.

// C# file exported to .winmd class library for use in metro app
namespace A
{
    public sealed class B
    {
        public B(bool bTest)
        {}

        // Other methods/members...
    }
}

// C++ metro app referencing .winmd created from C# above
...

A::B^ spB = ref new A::B(bTest);  // Throws an exception

Attempting to create an object of type B from the C# module in C++ would throw an exception, with a somewhat cryptic "WinRT transform error" show in the output log.

To fix this, I was able to do what DRapp suggested and add a default constructor to B:

// C# file exported to .winmd class library for use in metro app
namespace A
{
    public sealed class B
    {
        public B()
        {}
        public B(bool bTest)
        {}

        // Other methods/members...
    }
}

No more exception. :)




回答3:


it sounds like you don't have two constructors... (overloaded) for your class such as

public class YourClass
{
   public YourClass()
   {
   }


   public YourClass(String OneParameter)  // this OVERLOADS the default No parameter one
   {
      DoWhatever with your OneParameter...
   }
}


来源:https://stackoverflow.com/questions/3189139/class-library-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!