---
# System prepended metadata

title: C# - delegate practice

---

# C# - delegate practice

使用委派，印出靠左、靠右、等腰置中星號三角形

```csharp=
using System;

namespace ConsoleApp1
{
	internal class Program
	{
		static void Main(string[] args)
		{
			var left = new Triangle();
			string result = left.GetTriangle(5, (stars, i, num) => stars);
			Console.WriteLine(result);

			var right = new Triangle();
			string result2 = right.GetTriangle(5, (stars, i, num) => stars.PadLeft(num * 2));
			Console.WriteLine(result2);

			var isosceles = new Triangle();
			string result3 = isosceles.GetTriangle(5, (stars, i, num) => stars.PadLeft(num + i - 1).PadRight((i - 1) * 2 + 1, '*'));
			Console.WriteLine(result3);
		}
	}
	public class Triangle
	{
		public string GetTriangle(int num, Func<string, int, int, string> func)
		{
			string result = "";
			for (int i = 1; i <= num; i++)
			{
				string stars = new string('*', (i - 1) * 2 + 1);
				result += $"{func(stars, i, num)}\n";
			}
			return result;
		}
	}
}

```

數學很難算呃呃呃呃 :crying_cat_face: 