问题在代码中有更好的解释:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace heavynumbers2
{
class Program
{
static void Main(string[] args)
{
HeavyDeciCount();
int firstNumber;
int secondNumber;
Console.Write("Enter First Number: ");
firstNumber = int.Parse(Console.ReadLine());
Console.Write("Enter Second Number: ");
secondNumber = int.Parse(Console.ReadLine());
}
public static void HeavyDeciCount(int firstNumber, int secondNumber)
{
var totalHeavyCount = 0;
for (int i = firstNumber; i <= secondNumber; i++)
{
var avg = i.ToString()
.Select(o => Convert.ToInt32(o.ToString()))
.ToArray()
.Average();
var isHeavy = false;
if (avg > 7)
{
isHeavy = true;
totalHeavyCount++;
}
Console.WriteLine("HeavyNumbers" + "Average" + "IsHeavy");
Console.WriteLine(i + " " + avg + " " + (isHeavy ? "Yes" : "No"));
}
Console.WriteLine("Total Heavy Count: " + totalHeavyCount);
Console.WriteLine("Press Enter to Close Program ");
Console.ReadLine();
}
}
}
答案 0 :(得分:2)
您可以在静态方法中使用self
来引用类型(与在实例方法中使用self
的实例相比)
class A {
class func thefunc() -> A.Type {
return self
}
}
class B: A { }
let metaTypeA = A.thefunc() // A.Type
let metaTypeB = B.thefunc() // B.Type
同样,您可以使用运行时内省,特别是subjectType
Mirror
表示的self
属性。
实例变量
...
var subjectType: Any.Type
反映主体的静态类型。
来自the swiftdoc.org reference of Mirror
structure。
E.g:
class A {
class func thefunc() {
print(Mirror(reflecting: self).subjectType)
}
}
class B: A { }
A.thefunc() // A.Type
B.thefunc() // B.Type
或者,如果您不需要实际使用元类型(只是&#34;静态调用者和#34;之间不同),您可以使用String
self
表示}}
class A {
class func thefunc() -> String {
return String(self)
}
}
class B: A { }
print(A.thefunc()) // A
print(B.thefunc()) // B