---
# System prepended metadata

title: C# - delegate practice(inverted triangle)

---

# C# - delegate practice(inverted triangle)
只用一支method, 傳入委派來畫出正、倒的靠左、靠右、置中三角形（共六種）
```csharp=
using System;

namespace DelegatePractice
{
	internal class Program
	{
		static void Main(string[] args)
		{
			int rows = 5;
			//靠左正三角形
			var left = new Triangle();
			string leftResult = left.GetTriangle(rows, stars => new string('*', stars));
			Console.WriteLine(leftResult);

			//靠右正三角形
			var right = new Triangle();
			string rightResult = right.GetTriangle(rows, stars => new string('*', stars).PadLeft(rows));
			Console.WriteLine(rightResult);

			//置中正三角形
			var isosceles = new Triangle();
			string isoscelesResult = isosceles.GetTriangle(rows, stars => new string(' ', rows - stars) + new string('*', stars * 2 - 1));
			Console.WriteLine(isoscelesResult);

			//靠左倒三角形
			var invertedLeft = new Triangle();
			string result = invertedLeft.GetTriangle(rows, stars => new string('*', rows - stars + 1));
			Console.WriteLine(result);

			//靠右倒三角形
			var invertedRight = new Triangle();
			string result2 = invertedRight.GetTriangle(rows, stars => new string('*', rows - stars + 1).PadLeft(rows));
			Console.WriteLine(result2);

			//置中倒三角形
			var invertedIsosceles = new Triangle();
			string result3 = invertedIsosceles.GetTriangle(rows, stars => new string(' ', stars - 1) + new string('*', (rows - stars + 1) * 2 - 1));
			Console.WriteLine(result3);
		}
	}
	public class Triangle
	{
		public string GetTriangle(int rows, Func<int, string> func)
		{
			string result = "";
			for (int i = 1; i <= rows; i++)
			{
				result += (func(i)) + "\n";
			}
			return result;
		}
	}
}

```
