【发布时间】:2011-05-27 12:03:06
【问题描述】:
StringBuilder first = new StringBuilder();
StringBuilder second = first;
String str = "Love";
有没有办法检查变量“second”是否为类型引用,而变量“str”是否为类型值?我一直在谷歌搜索仍然无法得到它,这里的 C# 非常新。我知道有 second.getType() 但这并不能让我知道 second 是否属于类型引用。
非常感谢。
附加信息
在这里,我想坦率地说,我正面临 C Sharp 的编程测试,当然这是一个开卷测试,因为我不在封闭或受限的课程中 :-) 。我更熟悉 PHP、C/C++、Perl,但在 C 语言方面非常陌生,但我喜欢学习它。这是他们的测试。我已经填写了几个函数,只漏掉了 2 或 3 个,分别是 ref 和 unref。如果您看到下面的代码,我需要在 PrintSortedData 函数中打印出 之间的引用类型。测试问题在代码的注释中。可能我还没有弄好编程逻辑。
/// The DataObject class stored with a key
class DataObject
{
public string key = "";
public int value = 0;
// Populate
public DataObject(string k, int v = 0)
{
key = k;
value = v;
}
}
class Program
{
static Hashtable Data = new Hashtable();
static string[] StaticData = new string[] { "X-Ray","Echo","Alpha", "Yankee","Bravo", "Charlie",
"Delta", "Hotel", "India", "Juliet", "Foxtrot","Sierra",
"Mike","Kilo", "Lima", "November", "Oscar", "Papa", "Qubec",
"Romeo", "Tango","Golf", "Uniform", "Victor", "Whisky",
"Zulu"};
static void Main(string[] args)
{
for (int i = 0; i < StaticData.Length; i++)
Data.Add(StaticData[i].ToLower(), new DataObject(StaticData[i]));
while (true)
{
PrintSortedData();
Console.WriteLine();
Console.Write("> ");
string str = Console.ReadLine();
string[] strs = str.Split(' ');
if (strs[0] == "q")
break;
else if (strs[0] == "print")
PrintSortedData();
else if (strs[0] == "swap")
Swap(strs[1], strs[2]);
else if (strs[0] == "ref")
Ref(strs[1], strs[2]);
else
Console.WriteLine("Invalid Input");
}
}
/// <summary>
/// Create a reference from one data object to another.
/// </summary>
/// <param name="key1">The object to create the reference on</param>
/// <param name="key2">The reference object</param>
static void Ref(string key1, string key2)
{
}
/// <summary>
/// Removes an object reference on the object specified.
/// </summary>
/// <param name="key">The object to remove the reference from</param>
static void UnRef(string key)
{
// Populate
}
/// <summary>
/// Prints the information in the Data hashtable to the console.
/// Output should be sorted by key
/// References should be printed between '<' and '>'
/// The output should look like the following :
///
///
/// Alpha...... -3
/// Bravo...... 2
/// Charlie.... <Zulu>
/// Delta...... 1
/// Echo....... <Alpha>
/// --etc---
///
/// </summary>
static void PrintSortedData()
{
// Populate
ArrayList keys = new ArrayList(Data.Keys);
keys.Sort();
foreach (object obj in keys)
{
Console.Write(obj + "......." + ((DataObject)Data[obj]).value + "\n");
}
}
}
【问题讨论】:
-
first、second和str是所有引用。在这种情况下,first和second都指向同一个对象。