简体   繁体   中英

C# custom types?

I'm working on a calculator that uses polynomials, and I was wondering if I could make some sort of "custom type" to use instead of and array of lists of strings.

So, for example, instead of List<string>[] polynomial I'd like to write Polynomial polynomial , where the Polynomial type is a List<string>[] (which means I could use it the same exact way I currently use the List<string>[] , so, for example, I could access the values with polynomial[n][i] like I do now)

Is there any way to do this?

As suggested by @BionicCode I used an inheritant Polynomial class

public class Polynomial : List<List<string>>
{

}

and it works as expected. I did have to change List<string>[] to List<List<string>> beacuse otherwise it would throw a "invalid base type" error, but it still functions the same way:

Polynomial polynomial;

to create a new variable and

polynomial[n][i]

to access its values.

To instantiate a new Polynomial I use

polynomial = new Polynomial();
    
for (int i = 0; i < length; i++)
{
    polynomial.Add(new List<string>());
}

Use the following code for Polynomial class.

public class Polynomial
{
    public List<Monomial> monomials = new List<Monomial>();

    public Polynomial(List<Monomial> allMonomials)
    {
        monomials = allMonomials;
    }

    public Polynomial()
    {
        monomials = new List<Monomial>();
    }
}

And use the code below for Monomial class.

    public class Monomial
{
    public List<string> items = new List<string>();

    public Monomial()
    {
        items = new List<string>();
    }

    public Monomial(List<string> allItems)
    {
        items = allItems;
    }
}

To sum up, you can create new objects of Monomial and Polynomial as simple as you can see in the following code

List<Monomial> monomials = new List<Monomial>();
monomials.Add(new Monomial(new List<string>() {"A", "B", "C"}));
monomials.Add(new Monomial());
Polynomial polynomial = new Polynomial();
Polynomial polynomial2 = new Polynomial(monomials);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM