C#定义一个列表例子
时间: 2023-07-12 14:06:34 浏览: 48
以下是一个使用C#定义列表的例子:
```
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个字符串类型的列表
List<string> names = new List<string>();
// 添加元素到列表
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
// 遍历列表并输出元素
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
```
在上面的代码中,我们使用 `List<string>` 类型定义了一个名为 `names` 的列表。然后,我们使用 `Add` 方法向列表中添加了三个字符串元素。最后,我们使用 `foreach` 循环遍历列表中的元素,并将其输出到控制台。
相关问题
c#定义类例子
下面是一个简单的 C# 类的示例:
```csharp
public class Person
{
// 定义属性
public string Name { get; set; }
public int Age { get; set; }
// 定义方法
public void SayHello()
{
Console.WriteLine("Hello, my name is " + Name + " and I am " + Age + " years old.");
}
}
```
在上面的代码中,我们定义了一个名为 `Person` 的类,它具有两个属性 `Name` 和 `Age`,以及一个方法 `SayHello`,该方法将打印出一条问候语,其中包含对象的名称和年龄。
我们可以使用以下方式创建一个 `Person` 对象并调用其 `SayHello` 方法:
```csharp
Person person = new Person();
person.Name = "Bob";
person.Age = 30;
person.SayHello(); // 输出: Hello, my name is Bob and I am 30 years old.
```
C#wcf请举一个例子
好的,下面是一个简单的 C# WCF 服务的例子:
首先,在 Visual Studio 中创建一个新的 WCF 服务应用程序项目。然后,在服务契约中定义一个简单的操作:
```C#
[ServiceContract]
public interface IMyService
{
[OperationContract]
string GetMessage(string name);
}
```
这个操作接受一个字符串类型的参数,返回一个字符串类型的消息。
接下来,在服务实现中实现这个操作:
```C#
public class MyService : IMyService
{
public string GetMessage(string name)
{
return "Hello, " + name + "!";
}
}
```
这个实现接受一个字符串类型的参数,返回一个拼接了该参数的消息。
然后,在配置文件中定义一个终结点:
```XML
<system.serviceModel>
<services>
<service name="MyService">
<endpoint address="http://localhost:8080/MyService"
binding="basicHttpBinding"
contract="IMyService"/>
</service>
</services>
</system.serviceModel>
```
这个终结点定义了服务的地址、绑定和契约等信息。
最后,在 host 中启动服务:
```C#
ServiceHost host = new ServiceHost(typeof(MyService));
host.Open();
```
这个 host 启动了 MyService 类型的服务。
现在,WCF 服务已经启动并且可以接收客户端的请求。在客户端中,你可以使用类似下面的代码来调用服务:
```C#
ChannelFactory<IMyService> factory = new ChannelFactory<IMyService>(
new BasicHttpBinding(),
new EndpointAddress("http://localhost:8080/MyService"));
IMyService proxy = factory.CreateChannel();
string message = proxy.GetMessage("World");
Console.WriteLine(message);
```
这个客户端创建了一个 IMyService 类型的代理对象,并调用了它的 GetMessage 方法,将 "World" 作为参数传递,并将返回的消息打印到控制台上。
这就是一个简单的 C# WCF 服务的例子,它展示了如何定义服务契约、实现服务操作、配置服务终结点和启动服务 host。