C# 有些部分我不知道';我不明白
C#代码: ((姓名)名称1)做什么 有人能提供一些关于这些代码部分如何工作的提示或反馈吗?你能把我引向正确的方向吗?首先:C# 有些部分我不知道';我不明白,c#,C#,C#代码: ((姓名)名称1)做什么 有人能提供一些关于这些代码部分如何工作的提示或反馈吗?你能把我引向正确的方向吗?首先:string n1=((名称)name1)。FirstName (名称)名称1,一般可写成(类型)变量。这样做的目的是获取变量并尝试将变量name1强制转换为类型Name。这样我们就可以访问FirstName属性 在此处了解更多信息: 第二:公共无效排序(比较器比较) 这是一个方法声明 public表示可访问性。其他选项包括private、protected和其他一些
string n1=((名称)name1)。FirstName
,一般可写成(名称)名称1
。这样做的目的是获取变量并尝试将变量(类型)变量
强制转换为类型name1
。这样我们就可以访问Name
属性FirstName
- 在此处了解更多信息:
公共无效排序(比较器比较)
这是一个方法声明
表示可访问性。其他选项包括public
、private
和其他一些选项protected
表示任何引用此对象实例的代码都可以调用此方法public
表示返回类型void
是一个特殊的关键字,表示该方法不返回任何值void
是方法名称Sort
:Compare-Compare
是要传入的参数类型,Compare
是可在整个方法中使用的参数名称Compare
- 在此处了解更多信息:
using System;
// this is the delegate declaration
public delegate int Comparer(object obj1, object obj2);
public class Name
{
public string FirstName = null;
public string LastName = null;
public Name(string first, string last)
{
FirstName = first;
LastName = last;
}
// this is the delegate method handler
public static int CompareFirstNames(object name1, object name2)
{
string n1 = ((Name)name1).FirstName;
string n2 = ((Name)name2).FirstName;
if (String.Compare(n1, n2) > 0)
{
return 1;
}
else if (String.Compare(n1, n2) < 0)
{
return -1;
}
else
{
return 0;
}
}
public override string ToString()
{
return FirstName + " " + LastName;
}
}
class SimpleDelegate
{
Name[] names = new Name[5];
public SimpleDelegate()
{
names[0] = new Name("Joe", "Mayo");
names[1] = new Name("John", "Hancock");
names[2] = new Name("Jane", "Doe");
names[3] = new Name("John", "Doe");
names[4] = new Name("Jack", "Smith");
}
static void Main(string[] args)
{
SimpleDelegate sd = new SimpleDelegate();
// this is the delegate instantiation
Comparer cmp = new Comparer(Name.CompareFirstNames);
Console.WriteLine("\nBefore Sort: \n");
sd.PrintNames();
// observe the delegate argument
sd.Sort(cmp);
Console.WriteLine("\nAfter Sort: \n");
sd.PrintNames();
}
// observe the delegate parameter
public void Sort(Comparer compare)
{
object temp;
for (int i=0; i < names.Length; i++)
{
for (int j=i; j < names.Length; j++)
{
// using delegate "compare" just like
// a normal method
if ( compare(names[i], names[j]) > 0 )
{
temp = names[i];
names[i] = names[j];
names[j] = (Name)temp;
}
}
}
}
public void PrintNames()
{
Console.WriteLine("Names: \n");
foreach (Name name in names)
{
Console.WriteLine(name.ToString());
}
}
}
string n1 = ((Name)name1).FirstName;
public void Sort(Comparer compare)