简体   繁体   English

用字符串值设置属性

[英]Setting a property with a string value

I have a class Category with two a property name as string. 我有一个类别Category,其中两个属性名称为字符串。

and have a other class that use this class. 并拥有另一个使用此类的类。

Public Class Myclass
{
      public virtual Category Category
    {
        get;
        set;
    }
}

I have a object of Myclass. 我有一个Myclass对象。 I want set string value for Category Property of this object . 我想为该对象的Category属性设置字符串值。

Myclass cls=new Myclass();
cls.Category=// a string value

How to set this ? 如何设置呢?

From your example: 从您的示例:

Public Class Myclass
{
      public virtual Category Category
    {
        get;
        set;
    }
}

I am thinking you mean this: 我想你的意思是:

Public Class Myclass
{
      public string Category { get; set; } // variable
      public MyClass() {}  //<- empty constructor-might be created by default .. but I like to put them in
}

then call: 然后致电:

Myclass cls=new Myclass();
cls.Category= "text here";

It looks like your type for the Category variable is Category instead of string? 看来您Category变量的类型是Category而不是字符串?

Unless you already have a Category type somewhere that you want to use. 除非您已经要使用某个类别的类别。

Hope this helps! 希望这可以帮助!

For example, if one of those string properties is "Name" then you just set it like this: 例如,如果这些字符串属性之一是“名称”,则可以这样设置:

Myclass cls=new Myclass();
cls.Category = new Category();
cls.Category.Name = "CategoryName1";

Note that the Name property must be accessible to the calling code (eg public ). 注意,调用代码必须可以访问 Name属性(例如public )。

Or you can write it like this: 或者您可以这样写:

Myclass cls=new Myclass();
cls.Category = new Category {Name = "CategoryName1"};

Is this what you meant? 这是你的意思吗?

public class Category
{
   public string Name { get; set; }
   public string Description { get; set; }
}


Category myCategory = new Category();
myCategory.Category.Name = "Basketball";
myCategory.Category.Description = "Played Indoors";


Tutorial Reference: Below are some examples to help you understand properties and class's 教程参考:以下是一些示例,可帮助您了解属性和类的

Tutorial 1 教程1

Tutorial 2 教程2

You cannot set string value to non-string field. 您不能将字符串值设置为非字符串字段。 But if you need that string inside class instance, you can write like this: 但是,如果您需要在类实例中使用该字符串,则可以这样编写:

public class MyClass
{
    public Category Category { get; set; }
}

public class Category
{
    public Category(string name)
    {
        Name = name;
    }

    public string Name { get; set; }
}

And then declare Category field of MyClass like this: 然后像这样声明MyClass的Category字段:

var cls = new MyClass();
cls.Category = new Category("hello");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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