我是 C# 新手,习惯了 Swift,所以请耐心等待。
我想完全按照下面 Swift 代码描述的方式使用 C# 中的类型:
typealias Answer = (title: String, isCorrect: Bool)
typealias Question = (Question: String, Answers: [Answer])
再举个例子,现在使用上面的
Question
可以非常简单地在 swift 中制作 typealias
:
Question(Question: "What is this question?", Answers: [("A typedef", false), ("FooBar", false), ("I don't know", false), ("A Question!", true)])
我已经尝试使用
using
语句并创建抽象类,但到目前为止没有成功。
提前致谢。
这个帖子很旧,但我想添加一个简单的答案,因为现有的答案都不是。
C# 没有与
typealias
完全等价的:
Swift 中的
typealias
定义是持久的,可以在其他地方重用。 using
定义仅保留在定义它的文件中。它不能用于项目的其他部分。 我从未使用过 Swift,但看到你的示例代码,我能记得的最接近的想法是 匿名类型。它们允许您在声明变量并实例化其对象/值时构造一个新对象,而无需显式声明类/结构。示例:
var student = new
{
Name = "John",
LastName = "Doe",
Age = 37,
Hobbies = new [] { "Drinking", "Fishing", "Hiking" }
};
然后您可以访问
student.LastName
、student.Age
等字段。匿名类型内的属性类型由编译器推断(但如果您想强制某些属性使用特定类型,则可以使用强制转换)。
您的示例可以建模为类似的内容:
var answersArray = new[] {
new { Title = "First answer", IsCorrect = false },
new { Title = "Second answer", IsCorrect = true },
new { Title = "Third answer", IsCorrect = false },
new { Title = "Fourth answer", IsCorrect = false },
};
var questionData = new { Question = "To be or not to be?", Answers = answersArray };
数据将以某种方式访问,例如:
Console.WriteLine(questionData.Question);
foreach (var answer in answersArray)
Console.WriteLine(answer.Title);
匿名类型的问题是创建的对象是只读,因此匿名类型对象的属性接收到的值在对象实例化后无法更改。
using
关键字可用于您实际上已经定义了类的情况,并且您希望为该类提供别名,如下所示:
// The "HttpClient" class will now have an alias of "MyClient"
using MyClient = System.Net.Http.HttpClient;
这种方法显然需要预先定义您要别名的类,所以我不知道它是否符合您的需求。
经过这些考虑,我想说最佳实践(以及我的建议)实际上是在代码中实际声明类和/或结构来表示您正在使用的数据,而不是试图模仿 Swift 的
typealias
。
如果我没有误解的话,您想要类似于别名值元组的能力。值元组是 C# 的最新补充,让您可以创建对象(由
ValueTuple<T,T,T,T>
支持),而无需定义完整的类。例如:
public (string Name, int Age) GetPerson()
{
return (Name: "John", Age: 30);
}
var john = GetPerson();
Console.WriteLine(john.Age); // 30
目前,可以在 C# 中为类型添加别名(见下文),但还无法对值元组执行此操作。有一个开放的 GitHub 问题。
using Abc = String;
Abc test = "hello";
与此同时,最好创建类来表示您的数据(除非在某些情况下匿名类型就足够了,请参阅 vinicius.ras 的答案),例如:
public class Answer
{
public string Title {get;set;}
public bool IsCorrect {get;set;}
}
public class Question
{
public string QuestionText {get;set;}
public IList<Answer> Answers {get;set;}
}
我参加聚会有点晚了(5 年),但现在 C# 有了与
typealias
指令“有点”对应的 using
。例如,如果我们有一个这样的类:
namespace MyClasses;
public class Attribute
{
public string Name { get; set; }
}
然后为了避免与.NET
Attribute
类冲突,我们可以为其声明一个别名:
using System;
global using MyAttribute = MyClasses.Attribute;
namespace MyClasses;
public class NewAttribute: Attribute
{
private MyAttribute _attribute;
}
这里有趣的是,
global
意味着这个别名将可用于整个项目。如果没有此子句,它将仅在声明它的文件中可见。